> Oh? So in an example where B has a method m, and A inherits from B, how is it that `this` refers to something different when calling B.m() than when calling A.m()? They're the exact same function.
Just like in regular class-based OO languages, "this" is an implicit argument of every method that refers to the object on which the method was invoked.
You can even avoid manually doing all the "this" juggling yourself: Make a delegate class, which holds a reference to a method (including its captured variables) and a reference to the "this" object. When a method is retrieved from a an object, actually construct a delegate referencing both the method and the object. (If the method is retrieved after traversing the inheritance chain "upwards", fix the "this" reference along the way "downwards".) Finally, when a delegate is assigned to a variable or as a member of another object, get rid of the "this" reference and assign the method only instead. Client code never gets to see the "this" juggling.
Oh I know how to implement it, I was just responding to your claim that it was "an implementation detail of JavaScript functions." It's an implementation detail of method calls, the function itself is completely this-agnostic. I guess I was just being pedantic ;)
Just like in regular class-based OO languages, "this" is an implicit argument of every method that refers to the object on which the method was invoked.
You can even avoid manually doing all the "this" juggling yourself: Make a delegate class, which holds a reference to a method (including its captured variables) and a reference to the "this" object. When a method is retrieved from a an object, actually construct a delegate referencing both the method and the object. (If the method is retrieved after traversing the inheritance chain "upwards", fix the "this" reference along the way "downwards".) Finally, when a delegate is assigned to a variable or as a member of another object, get rid of the "this" reference and assign the method only instead. Client code never gets to see the "this" juggling.