3 ms·
An OO JS tutorial should also include a discussion of the this pointer, and how it's not like other OO languages. In JS, this reflects the context of the calle
by jseims 14y ago
An OO JS tutorial should also include a discussion of the this pointer, and how it's not like other OO languages.
In JS, this reflects the context of the caller, not the object (which I think is messed up), so you have to learn call and apply.
- mdgrech23 14y agoMy first thought here was holy cow yes it should! My second though was ack, there's a lot to go over. Sounds like a good topic to cover in a second post. However if you see a way to nicely integrate into the current post in brevity I'm all ears and would be happy to update the post :) Thanks!
- tikhonj 14y agoThe problem is that in JavaScript functions (and, consequently, methods) are first-class citizens. If `this` reflected the value of the object, certain code would work oddly: var a = {fn : function () {this.doStuff()}}, b = {}; b.method = a.fn;// What now? So what JavaScript did actually makes some sense. Another viable solution would be to have `this` passed into a method explicitly, like in Python. Then the expression `a.b()` could desugar to something like `a.b(a)` with `b` expecting `this` as its first argument. This also has some disadvantages. You could also do like Lua and have a separate syntax for calling methods this way (a:b()), but this is also confusing. In short, there is no perfect solution.