"this" refers to "window" object not working as expected

Viewed 450

I experimented a bit with this keyword and I found a strange problem. When a variable is declared as var then this correctly refer to this variable. But if i declared the same variable as let or const then this lost reference and show undefined in console.

var prop = "outer"; // not working if let or const.

let foo = {
  prop: "inner",
  show() {
    console.log(this.prop)
  }
}

let a = foo.show;
let b = foo.show.bind(foo);
a()
b()

1 Answers

When you run this code outside of strict mode (as here), then the this keyword defaults to the global object - which in the browser is window. (In strict mode it would be undefined so a() will throw an error.)

The difference in behaviour between var and let/const is a simple consequence of the fact that var-declared global variables are the same thing as properties on the global (window) object, whereas that doesn't happen with variables (even global ones) declared with let or const.

See for example MDN:

Just like const the let does not create properties of the window object when declared globally (in the top-most scope).

Related