简体   繁体   中英

Equivalent of C extern declaration in JavaScript

Writing some JS and would love to enumerate specifically what I'm importing from other files in the main body of my JS script. Is there an equivalent to C's extern declaration for JS?

Thanks!

Variables declared outside of function scope are global in JavaScript. For example, if you have two JS files and declare a variable 'myObject' in the first file, it will be in scope for the second file, and declared for use if the first file is loaded into the browser already.

If you need access to objects between JS files, it's good practice to expose one object to the global namespace and declare fields and methods on that object.

File 1:

var myObject;
myObject.myField = "Field!";    

File 2:

myObject.prototype.myFunction = function () {
    return this.myField;
};

Hope this helps, happy to hear other suggestions and open to corrections :D

There's no equivalent to a C extern declaration in JavaScript because JavaScript doesn't require variables to be declared before they're used the way C does.

If your JavaScript code depends on some properties being defined on the window object, just document those properties in a comment near the top of the file.

Sadly, Javascript has no built in features for controlling what gets imported or not.

By default, all sripts loaded in a page will write their global variables to the same shared global scope. The only way around this is writing your scripts so that they create as few global variables as possible, using the module pattern .

Alternatively you can use one of the module systems extensions that people came up with. For example you can write your scripts using the CommonJS module system and it will make it make it so that top level var declarations in your scripts arent seen from other scripts and lets you explicitly export the values you like. Some runtimes like nodejs can run CommonJS modules natively and for the ones that dont, like browsers, you can use a tool like browserify to compile the commonjs modules into a single file that can be put into a script tag and that will still do the right thing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM