JavaScript声明变量和未声明变量之间的主要区别是什么,因为delete操作符不能对声明变量起作用?
var y = 43; // declares a new variable
x = 42;
delete x; // returns true (x is a property of the global object and can be deleted)
delete y; // returns false (delete doesn't affect variable names)
这一切为什么要发生?全局声明的变量也是window对象的属性,那么为什么不能删除它呢?
发布于 2013-04-15 03:43:10
已声明和未声明的全局变量
存储和访问它们的机制是相同的,但是在某些情况下,根据configurable
属性的值(如下所述),JavaScript会对它们进行不同的处理。在常规使用中,它们的行为应该是相同的。
两者都存在于全局对象中
下面是已声明和未声明的全局变量的一些比较。
var declared = 1; // Explicit global variable (new variable)
undeclared = 1; // Implicit global variable (property of default global object)
window.hasOwnProperty('declared') // true
window.hasOwnProperty('undeclared') // true
window.propertyIsEnumerable('declared') // true
window.propertyIsEnumerable('undeclared') // true
window.declared // 1
window.undeclared // 1
window.declared = 2;
window.undeclared = 2;
declared // 2
undeclared // 2
delete declared // false
delete undeclared // true
delete undeclared // true (same result if delete it again)
delete window.declared // false
delete window.undeclared // true (same result if delete it yet again)
delete window.undeclared // true (still true)
已声明和未声明的全局变量都是window
对象(默认全局对象)的属性。两者都不是通过原型链从不同的对象继承而来的。它们都直接存在于window
对象中(因为window.hasOwnProperty
对它们都返回true
)。
可配置属性
对于已声明的全局变量,configurable
属性为false
。对于未声明的全局变量,则为true
。可以使用getOwnPropertyDescriptor
方法检索configurable
属性的值,如下所示。
var declared = 1;
undeclared = 1;
(Object.getOwnPropertyDescriptor(window, 'declared')).configurable // false
(Object.getOwnPropertyDescriptor(window, 'undeclared')).configurable // true
如果属性的configurable
属性为true,则可以使用defineProperty
方法更改该属性的属性,并可以使用delete
运算符删除该属性。否则,不能更改属性,也不能以这种方式删除属性。
在non-strict mode中,如果属性是可配置的,则delete
操作符返回true
,如果属性是不可配置的,则返回false
。
摘要
声明的全局变量
删除属性是缺省全局对象的属性(window
)
delete
未声明的全局变量
window
)delete
运算符删除
delete
另请参阅
发布于 2013-04-13 08:38:51
主要的区别在于在函数中声明变量的时候。如果在函数内部声明变量时使用var
,那么该变量将成为局部变量。但是,如果不使用var
,那么无论在何处声明变量(在函数内部还是外部),变量都将成为全局变量。
发布于 2016-02-18 16:35:12
当通过JavaScript中的变量声明创建变量时,这些属性都是使用DontDelete属性创建的,这基本上意味着您创建的变量不能使用delete表达式删除。默认情况下,所有函数、参数和函数参数都是使用此DontDelete属性创建的。您可以将DontDelete看作是一面旗帜。
var y = 43;
delete y; //returns false because it is has a DontDelete attribute
而未声明的赋值不会设置任何像、DontDelete、这样的属性。因此,当我们在这个未声明的变量上应用删除操作符时,它返回true。
x = 42;
delete x; //returns true because it doesn't have a DontDelete attribute
属性赋值和变量声明的区别-后者设置DontDelete,而前一个不设置。这就是为什么未声明的赋值会创建一个可删除的属性。
https://stackoverflow.com/questions/15985875
复制