我們知道delete操作符只能刪除對象上的某些特殊屬性,該屬性的descriptor描述符必須滿足configurable描述符為true,方才可以刪除。
關于descriptor描述符
value,get,set,writable,configurable,enumerable
問個問題
現在了解了原理我們來回答一個問題,為什么delete操作符不能刪除var定義的變量,但是卻可以刪除沒有經過var定義的全局變量?
因為按理說每個全局變量都掛載到了this上面啊(無論nodejs中的global還是pc中的window)不能通過delete this.foo
進行刪除嗎?
delete is only effective on an object's properties. It has no effect on variable or function names.While sometimes mis-characterized as global variables, assignments that don't specify an object (e.g. x = 5) are actually property assignments on the global object.
或者你可以說,規范中就這么規定的,不能刪除聲明的變量和方法名。
configurable:false是導致該變量無法被刪除的原因。
所以,如果設置全局變量的時候對其configurable屬性描述符進行設置,就能使用delete操作符對該變量進行刪除了。
哪些屬性也不可以刪除?
//內置對象的內置屬性不能被刪除
delete Math.PI; // 返回 false
//你不能刪除一個對象從原型繼承而來的屬性(不過你可以從原型上直接刪掉它).
function Foo(){}
Foo.prototype.bar = 42;
var foo = new Foo();
// 無效的操作
delete foo.bar;
// logs 42,繼承的屬性
console.log(foo.bar);
// 直接刪除原型上的屬性
delete Foo.prototype.bar;
// logs "undefined",已經沒有繼承的屬性
console.log(foo.bar);
這個刪除效果應該和a=null;是等效的嗎?
Unlike what common belief suggests, the delete operator has nothing to do with directly freeing memory (it only does indirectly via breaking references. See the memory managementpage for more details).