如何删除用 Object.defineProperty 定义的 window getter
How to delete a window getter defined with Object.defineProperty
如果我这样做:
Object.defineProperty(window, 'hello',{
get: ()=>"hello to you!"
});
调用方式为:
你好
并回复
向你问好!
我该如何删除它?
您需要将另一个 属性 添加到您在 defineProperty
中传递的描述符对象,即 configurable: true
,之后您可以删除 属性 使用delete
运算符。
'use strict'
Object.defineProperty(window, 'hello',{
get: ()=>"hello to you!",
configurable: true //make this true
});
console.log(window.hello);
delete window.hello
// hello is deleted from window
console.log(window.hello);
默认情况下,如果您不将描述符对象的 configurable
设置为 true
,则它是假的,来自 docs:
configurable
true if and only if the type of this property descriptor may be
changed and if the property may be deleted from the corresponding
object. Defaults to false.
如果我这样做:
Object.defineProperty(window, 'hello',{
get: ()=>"hello to you!"
});
调用方式为:
你好
并回复 向你问好! 我该如何删除它?
您需要将另一个 属性 添加到您在 defineProperty
中传递的描述符对象,即 configurable: true
,之后您可以删除 属性 使用delete
运算符。
'use strict'
Object.defineProperty(window, 'hello',{
get: ()=>"hello to you!",
configurable: true //make this true
});
console.log(window.hello);
delete window.hello
// hello is deleted from window
console.log(window.hello);
默认情况下,如果您不将描述符对象的 configurable
设置为 true
,则它是假的,来自 docs:
configurable
true if and only if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object. Defaults to false.