Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 767
Hanfei Sun Avatar asked Dec 27 '25 18:12

Hanfei Sun


1 Answers

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));
like image 57
Quentin Avatar answered Dec 30 '25 22:12

Quentin



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!