Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using window as a prototype returns seemingly wrong values in javascript

Tags:

javascript

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)

like image 725
Amin Avatar asked Aug 19 '26 01:08

Amin


2 Answers

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!

like image 101
James Monger Avatar answered Aug 21 '26 15:08

James Monger


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
like image 35
Stubb0rn Avatar answered Aug 21 '26 13:08

Stubb0rn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!