我们知道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).