Hacker News new | ask | show | jobs
by nbouscal 4689 days ago
> that is an implementation detail of JavaScript functions.

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.

That said, I do need to clarify. I was talking about implementing classical inheritance with prototypal inheritance, and implementing prototypal inheritance with classical inheritance. You can implement either using base language features if you want to create a new object system, but that's not what I was referring to.

1 comments

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