x = 42; // creates the property x on the global object
var y = 43; // creates the property y on the global object, and marks it as non-configurable
// x is a property of the global object and can be deleted
delete x; // returns true
// y is not configurable, so it cannot be deleted
delete y; // returns false
Run Code Online (Sandbox Code Playgroud)
我不明白不可配置的意思是什么.为什么我不能删除y?
x = 42
Run Code Online (Sandbox Code Playgroud)
是相同的
window.x = 42
Run Code Online (Sandbox Code Playgroud)
即在window对象上创建属性.而
var y = 43
Run Code Online (Sandbox Code Playgroud)
表示'在本地范围内创建变量'.
delete x
Run Code Online (Sandbox Code Playgroud)
手段
delete window.x
Run Code Online (Sandbox Code Playgroud)
这可能符合您的期望,但您不能delete在局部变量上使用.来自文档
delete运算符从对象中删除属性.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete
(我的重点)
向对象添加属性时,可以使其可配置或不可配置.您的示例的长手版本:
x = 42;
Run Code Online (Sandbox Code Playgroud)
是
Object.defineProperty(window, 'x', {
value: 42,
writable: true,
configurable: true,
enumerable: true
});
Run Code Online (Sandbox Code Playgroud)
可以删除可配置属性,从而将它们从对象中删除(这可能会导致内存被恢复,但它不是直接的).
你也可以这样写:
window.x = 42;
Run Code Online (Sandbox Code Playgroud)
当我们谈到下一期时,这更加明显.
window.x = 42; // x is a property
var y = 43; // y is not a property
Run Code Online (Sandbox Code Playgroud)
这是你无法删除的真正原因y.它不是属性,也不附加到对象上.delete关键字用于从对象中删除属性.
对于y- 当无法访问时(或旧浏览器中引用计数为0时),它自然可用于垃圾收集.
您还可以阻止删除属性:
Object.defineProperty(window, 'x', {
value: 42,
writable: true,
configurable: false,
enumerable: true
});
Run Code Online (Sandbox Code Playgroud)
这将导致false尝试删除它的返回,或者如果您在严格模式下运行则会出错.
| 归档时间: |
|
| 查看次数: |
86 次 |
| 最近记录: |