Sunday 30 December 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

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...