我正在阅读有关 Javascript方法的这篇文章delete
,并尝试了以下代码:
function f(){
var x = "abcd";
console.log(delete x); //returns false, because x has DontDelete attribute
y = "abcd";
console.log(delete y); //returns true, but I didn't explicitly assign y as a property
}
这很奇怪,因为我没有使用属性赋值y
(如:) window.y="abcd";
,文章声称这是你如何使属性delete
能够。
为什么没有y
属性DontDelete
?
更新:
在下面的答案中,声称 y 是可删除的,仅仅是因为它是window
对象的属性。那不是真的。考虑以下代码段:
function f() {
var functionx = "abcd";
console.log(delete functionx); //returns false, because x has DontDelete attribute
functiony = "abcd";
console.log(delete functiony); //returns true, but I didn't explicitly assign functiony as a property to the window
}
//take 1
var globalx = "abcd";
console.log(this.globalx);//to prove x is a property of the global
console.log(delete globalx);//fails, even though x is a property of the window
//take 2
this.globaly = "abcd";
console.log(this.globaly);//to prove y is a property of the global
console.log(delete globaly);//succeeds, because I used property assignment
f();
在 take 1 中,globalx
是窗口的一个属性,但它仍然不可删除。是否delete
成功的标准不是变量是否是某物的属性(始终为真),而是该属性是否具有DontDelete
属性集。