Hanfei Sun
Hanfei Sun

Reputation: 47071

In browser, assign a new value to "window" object doesn't work?

In browser, I tried to evaluate the following snippet:

window = 1; console.log(window)

The value printed in console is still the original window object instead of number 1.

Does anyone have ideas about why window object can't be re-assigned? Is this a feature of Javascript language? Can I make my own object not writable like window object too?

Upvotes: 3

Views: 567

Answers (2)

James Thorpe
James Thorpe

Reputation: 32212

The specification says:

The window, frames, and self IDL attributes must all return the Window object's browsing context's WindowProxy object.

The "must" here implying that no matter what you do, every request to window will result in the WindowProxy object.

Upvotes: 1

Quentin
Quentin

Reputation: 943981

It can't be overwritten because it is defined as being non-writable.

That is a feature of JS (although the window object is probably implemented at a lower level).

var example = {};
Object.defineProperty(example, "foo", {
  value: "Hello",
  writable: false
});

document.body.appendChild(document.createTextNode(example.foo));
example.foo = "World";
document.body.appendChild(document.createTextNode(example.foo));

Upvotes: 3

Related Questions