3 ms·
The problem is that in JavaScript functions (and, consequently, methods) are first-class citizens. If `this` reflected the value of the object, certain code wou
by tikhonj 15y ago
The 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.