是否可以在 Javascript 中更改或删除全局对象的属性

Is it possible to alter or delete properties of the global object in Javascript?

本文关键字:删除 全局 对象 属性 Javascript 是否      更新时间:2023-09-26

我只是在阅读有关全局对象的内容,并且想知道是否可以更改全局对象属性的值。我不知道这会有什么目的,但我很感兴趣。

以这段代码为例:

Infinity = 4;           //Alter the property Infinity of the global object
                        //This doesn't prompt an error...
console.log(Infinity);  //Yet, for some reason it still prints Infinity, instead of 4.

你也可以这样做吗:

delete Infinity;
console.log(Infinity)

这似乎是不可能的,因为Infinity仍然打印Infinity,而不是提示一个未定义的错误。

这取决于 - 属性是否可写/可配置?

Infinity两者都不是,如以下控制台日志所示:

> Object.getOwnPropertyDescriptor(window,'Infinity')
< Object {value: Infinity, writable: false, enumerable: false, configurable: false}

但是,其他全局属性(如 frames)是可配置的:

> Object.getOwnPropertyDescriptor(window,'frames')
< Object {value: Window, writable: true, enumerable: true, configurable: true}

因此,基本上,这取决于属性的设置方式。

好问题,但答案是否定的。 无法修改或删除全局对象。 全局对象是必需的,并且内置于 JavaScript 中。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects