function woot:donk() ... end
woot:donk()
is equivalent to woot.donk = function(self) ... end
woot.donk(woot)
and when you define a function normally e.g. function() ... end
there is no self parameter, thus the one from the parent scope is captured. The flaw with JS, really, is that it forces every function to be a method, and doesn't let you express whether you are defining one or the other.(think I got this right, my Lua is a bit rusty)
Klass.method := lambda { p self }
Also, if JavaScript looked like this, you wouldn't need the fat arrow: // Let's call this a "prototype function"
Klass.prototype.function method() {
…
}
Together with these rules:* A function always captures its outer `this`
* The getter of a prototype function (`thing.method`) always returns a binded function (where `this` == `thing`).
I don't think that's true: functions accessed via objects could very well be bound to the object (that's what Python does, accessing a method via an object instance returns a "bound method" which is curried with the instance, whereas accessing the same method via the class returns an "unbound method" which requires a class instance as its first argument).
Klass.prototype.method = options.method;Not really, it's trivial to create a dict-like object which allows access to keys as properties, just override `__getattr__`.
> In JavaScript an object is an object is an object
No, objects can have a non-null [[prototype]] indicating it was created from using `new` on a constructor.
> Klass.prototype.method = options.method;
Depends what `options` is.
JavaScript is forced to make the pessimal choice of only ever having dynamic-bound "this", because of that favorite whipping boy ... prototypal inheritance.
If JavaScript had a notion of a class (even as a constructor function + prototype) definition, then it would be possible to tag methods with the correct instance reference, as in Ruby and in Python. Unfortunately, because the standard pattern for defining an instance method is:
... where the function is an expression just like any other, you have to have dynamic-bound this to make prototypes work correctly by default.