Sunday, December 30, 2018

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!


Answer




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


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...