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

标签 javascript object window getter

如果我这样做:

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

调用方式为:

你好

并回复 向你问好! 如何删除它?

最佳答案

您需要向您在defineProperty中传递的描述符对象添加另一个属性,即configurable: true,之后您可以使用删除运算符。

'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,则它为 false,来自 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.

关于javascript - 如何删除使用 Object.defineProperty 定义的窗口 getter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57452233/

相关文章:

javascript - Object(this) 是做什么的?

java - 在没有 JFrame 或 AWT 的情况下制作 Java 窗口

javascript - 如何在innerHTML标签中每隔几秒添加一个新图像而不破坏 "<br>"JavaScript,HTML5

javascript - 如何使用 google maps api V3 显示建筑物的室内平面图

javascript - 鼠标和触摸事件未按预期工作

javascript - 如何访问组件中的 vuejs webpack 配置变量?

c++ - 创建大量对象 C++

javascript - jQuery + 扩展 Object.prototype = "c.replace is not a function"

javascript - iPhone - Safari 父窗口焦点问题

javascript - 如何创建一个新窗口