3

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?

Hanfei Sun
  • 45,281
  • 39
  • 129
  • 237

2 Answers2

3

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));
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
1

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.

James Thorpe
  • 31,411
  • 5
  • 72
  • 93