you'd expect this code to return "123", but instead it returns the window object
function W() {
this.window = "123";
}
W.prototype = window;
(new W()).window; // window object, not "123"
please check followup question (window as prototype makes setTimeout behave oddly)
The window property on a global window object refers to itself, and it is immutable.
Therefore, the constructor W cannot set the property to 123.
window.window; // returns window object
window.window = "123";
window.window; // still returns window object
If you try to set a non-immutable property in your W constructor, you will see that it works correctly.
function W() {
this.notWindow = "123";
}
W.prototype = window;
(new W()).notWindow; // returns "123"
This is nothing to do with the prototype, and is instead to do with trying to set immutable properties. Very interesting question, though!
As it was already pointed out window.window is immutable, but you can define own window property in W() constructor function.
function W() {
Object.defineProperty(this, 'window', {
configurable: true,
enumerable: true,
writable: true,
value: '123'
});
}
W.prototype = window;
document.write(new W().window); //123
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With