简体   繁体   中英

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

I was just reading up stuff about the global object, and was wondering if it would be possible to alter the values of the properties of the global object. I do not know what purpose this would serve, yet am interested.

Take this code for example:

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.

Could you also do this:

delete Infinity;
console.log(Infinity)

It appears that this is impossible since Infinity still prints Infinity, instead of prompting an undefined error.

It depends - is the property writable/configurable or not?

Infinity is neither, as exposed by the following console log:

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

However, other global properties, such as frames , are configurable:

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

So, basically, it depends on how the property is set up.

Good question, but the answer is no. Global objects cannot be modified or deleted. Global objects are required and built-in to JavaScript.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM