Monday 18 June 2018

Define global variable in a JavaScript function



Is it possible to define a global variable in a JavaScript function?



I want use the trailimage variable (declared in the makeObj function) in other functions.
















Answer



Yes, as the others have said, you can use var at global scope (outside of all functions) to declare a global variable:







Alternately, you can assign to a property on window:







...because in browsers, all global variables global variables declared with var are properties of the window object. (In the latest specification, ECMAScript 2015, the new let, const, and class statements at global scope create globals that aren't properties of the global object; a new concept in ES2015.)



(There's also the horror of implicit globals, but don't do it on purpose and do your best to avoid doing it by accident, perhaps by using ES5's "use strict".)




All that said: I'd avoid global variables if you possibly can (and you almost certainly can). As I mentioned, they end up being properties of window, and window is already plenty crowded enough what with all elements with an id (and many with just a name) being dumped in it (and regardless that upcoming specification, IE dumps just about anything with a name on there).



Instead, wrap your code in a scoping function and use variables local to that scoping function, and make your other functions closures within it:





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...