0

I am quite confused, as my knowledge of javascript seem to have been outdated. I remember that the following:

p = {
    foo: function() {
        console.log(this);
    }
}

would have this not bound unless you used new to create a new instance with the object as prototype. Has this changed in recent years? It's been a very long time since I stopped coding in vanilla js so I might be wrong, or mixing different concepts together.

Stefano Borini
  • 138,652
  • 96
  • 297
  • 431
  • 1
    JS can't suddenly make a change like this without breaking a lot of stuff. – ggorlen Apr 16 '21 at 20:59
  • 3
    Your example will not bind `this`. The value of `this` will be determined by how the function is called. Can you give some more details about what you're seeing happen when you call it? – Nicholas Tower Apr 16 '21 at 20:59
  • @NicholasTower if I call p.foo() this will be p, but then... when is not bound to p? – Stefano Borini Apr 16 '21 at 21:00
  • Isn't all this covered in [How does the this keyword work?](/questions/3127429/how-does-the-this-keyword-work) – trincot Apr 16 '21 at 21:00
  • 2
    If you call `p.foo()`, then the fact that the code starts with `p.` will cause `this` to equal `p`. This is not locked in ahead of time, it's just a result of the way you called it. Change the code to `const temp = p.foo; temp()`, and `this` will no longer be `p`. – Nicholas Tower Apr 16 '21 at 21:01
  • 1
    What you remember is wrong. JS never worked that way. – Jonas Wilms Apr 16 '21 at 21:01
  • @NicholasTower ah yes. Now I remember how it works. Thanks. Getting old. Closing – Stefano Borini Apr 16 '21 at 21:02
  • `this` can best be understood as a fixed-named argument with index -1 which is passed when the call is made together with the "normal" arguments (if any). Some special rules apply, but if you understand this part, you get a long way. – trincot Apr 16 '21 at 21:05

0 Answers0