2

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()
Telirw
  • 373
  • 3
  • 15
  • 1
    @adiga I don't believe the duplicate you've marked is a good fit for this question. It does explain what is going on with the `a` call in this snippet - but the question seems to accept that, the question is more about why this doesn't happen when `let` or `const` is used, which as far as I can see isn't addressed at all in the linked question. (Although I haven't read all the comments.) – Robin Zigmond Oct 12 '20 at 19:39
  • "*`this` correctly refer to this variable.*" - no, that's never the correct behaviour. Sure, `this` may refer to the global object in sloppy mode when you don't call the method on context, but you should never *use* that "feature". In strict mode, `this` is properly `undefined`. – Bergi Oct 12 '20 at 19:40
  • @RobinZigmond Fixed with a proper duplicate target :-) – Bergi Oct 12 '20 at 19:40

1 Answers1

2

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).

Robin Zigmond
  • 17,805
  • 2
  • 23
  • 34