js var的作用

num1=1;定义的是一个全局(window)属性,可以通过window.num1访问,
Object.getOwnPropertyDescriptor(window, 'num1')
{value: 1, writable: true, enumerable: true, configurable: true}

可以看到num1是可变,可遍历(keys(window)或for key in window),可配置的。
configurable
true if and only if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object.

就是说configurable是false,则不能用delete删除的。

var test=1;
Object.getOwnPropertyDescriptor(window, 'test')
{value: 1, writable: true, enumerable: true, configurable: false}


由此可见不加var相当于给window加了一个configurable=true的属性,加var相当于给window加了一个configrable=false的属性。

另外let和const定义的变量也是configurable=false。

还可以通过Object.definedProperty(window, 'num3', {configurable:true, writable:true, enumerable:false, value:3})来详细定义对象的属性。

猜你喜欢

转载自lg-asus.iteye.com/blog/2395907