Ad

Why Can't I Reassign Window.document Property?

- 1 answer

I'm playing with Javascript and discovered that I can't change default value(provided by a browser) of window.document object.

window.document = 3;
console.log(window.document);

I tried to console.log(window) in order to see something like read-only property in document object but didn't find anything.

It seems like some kind of magic and I want to know why this is happening.

Ad

Answer

Thanks for nice question. Under the hood properties can have a descriptors. And we can easily deal with them. Like here:

const dsc = Object.getOwnPropertyDescriptor(window, 'document');
console.log(dsc);

And if you check the result you will see that document property just doesn't have a setter. That's why you can't re-assign it.

And here you can find some more information about descriptors

Ad
source: stackoverflow.com
Ad