简体   繁体   中英

JavaScript global variable declaration syntax

I'm writing a Javascript library that I hope to be able to minify with the Closure Compiler's ADVANCED_OPTIMIZATIONS option. The library has maybe two dozen global variables which set lower and upper range limits, string literals, etc.

To make these variable accessible from other source files and to avoid dead code removal, I have to "export" them. See Advanced Compilation and Externs .

Therefore, rather than declare variables with this syntax:

var fooMinValue = 10;

I plan to use this syntax:

 window['fooMinValue'] = 10;

I've tested this and it seems to work fine. My questions are, is there any downside to using this syntax and is it supported in all browsers released since IE 6? (Or should I be using a completely different technique altogether?)

Although both are properties of the global object, there is a difference: when you declare the variable with var , its [[Configurable]] internal attribute gets set to false . Therefore, it's not possible to change its attributes with Object.defineProperty (except for [[Value]] ). The most notable effect is that such variables cannot be delete d:

​var foo = 'bar';
window['bar'] = 'baz';
console.log(foo); // 'bar'
console.log(bar); // 'baz'
delete foo;       // doesn't work, you can't delete vars
delete bar;       // works, bar is an object property
console.log(foo); // 'bar'
console.log(bar); // ReferenceError

Also, when assigning a variable to a property, you make a COPY of the value instead of referencing the variable. This means external changes to the property don't affect the value of the variable.

(function() {
  var foo = 'bar';
  window['foo2'] = foo; //export foo
  console.log(foo);  // will output 'bar'
  setTimeout(function() { console.log(foo) }, 1000); //will output 'bar'
})();
window['foo2'] = 'baz';
console.log(window['foo2']); // will output 'baz'

The above code will produce the following output:

'bar'
'baz'
'bar'

It is the same except that if your script is not running on a browser it is very probable that window will be undefined.

You are welcome!

It will work; it's perfectly valid syntax; and it's supported in IE6 and up.

Demo: http://ie6test.it/?url=http://jsbin.com/usafeg/2

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