我們知道delete操作符只能刪除對(duì)象上的某些特殊屬性帖汞,該屬性的descriptor描述符必須滿足configurable描述符為true,方才可以刪除。
關(guān)于descriptor描述符
value回挽,get,set,writable同衣,configurable蚜枢,enumerable
問個(gè)問題
現(xiàn)在了解了原理我們來回答一個(gè)問題缸逃,為什么delete操作符不能刪除var定義的變量,但是卻可以刪除沒有經(jīng)過var定義的全局變量厂抽?
因?yàn)榘蠢碚f每個(gè)全局變量都掛載到了this上面靶杵怠(無論nodejs中的global還是pc中的window)不能通過delete this.foo
進(jìn)行刪除嗎?
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.
或者你可以說昭殉,規(guī)范中就這么規(guī)定的,不能刪除聲明的變量和方法名藐守。
configurable:false是導(dǎo)致該變量無法被刪除的原因挪丢。
所以,如果設(shè)置全局變量的時(shí)候?qū)ζ鋍onfigurable屬性描述符進(jìn)行設(shè)置卢厂,就能使用delete操作符對(duì)該變量進(jìn)行刪除了乾蓬。
哪些屬性也不可以刪除?
//內(nèi)置對(duì)象的內(nèi)置屬性不能被刪除
delete Math.PI; // 返回 false
//你不能刪除一個(gè)對(duì)象從原型繼承而來的屬性(不過你可以從原型上直接刪掉它).
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"任内,已經(jīng)沒有繼承的屬性
console.log(foo.bar);
這個(gè)刪除效果應(yīng)該和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).