虽然两者都是全局对象的属性,但还是有区别的:当你用 声明变量时var
,它的[[Configurable]]
内部属性被设置为false
。Object.defineProperty
因此,不能用(除了)来改变它的属性[[Value]]
。最显着的效果是此类变量不能为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
此外,将变量分配给属性时,您会复制该值而不是引用该变量。这意味着对属性的外部更改不会影响变量的值。
(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'
上面的代码将产生以下输出:
'bar'
'baz'
'bar'