如何删除使用 Object.defineProperty 定义的窗口 getter

Zib*_*bri 2 javascript getter window object

如果我这样做:

Object.defineProperty(window, 'hello',{ 
   get: ()=>"hello to you!"
});
Run Code Online (Sandbox Code Playgroud)

其调用方式为:

你好

并向您回复您好!我该如何删除它?

Ful*_*Guy 5

您需要向传入的描述符对象添加另一个属性defineProperty,即configurable: true,之后您可以使用运算符删除属性 buy 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);
Run Code Online (Sandbox Code Playgroud)

默认情况下,如果您不为描述符对象创建configurableas ,则它是 false,来自文档true

可配置

true 当且仅当该属性描述符的类型可以更改并且该属性可以从相应的对象中删除时。默认为 false。