3 ms·
I'd say it's a fundamental language design question of how to properly mix classes and first-class functions, and there's no clear answer. More specifically, if
by alangpierce 8y ago
I'd say it's a fundamental language design question of how to properly mix classes and first-class functions, and there's no clear answer. More specifically, if you access `myInstance.myMethod` without invoking it, what should happen? Should it "carry along" `myInstance`, and how should that work? Different languages have different answers:
* In Java, their solution is to simply not have first-class functions, so the syntax isn't possible. Method invocation (`myInstance.myMethod()`) is a special syntactic form; it's not just a property access and function invocation. There's a special `myInstance::myMethod` syntax that's like a lambda and behaves as expected, including allocating a new instance each time it's used.
* In Python, `myInstance.myMethod` always allocates a new function object, just like `myInstance.myMethod.bind(myInstance)` would do in JS. This avoids the mistakes from JS, but is a bit magical and inefficient (though I'm sure the implementation can optimize it). For example, `arr.append is arr.append` is false because simply accessing a method creates a new function object, so you'll get two different function objects. Still, this has a certain elegance because method invocation doesn't need to be seen as a special syntax like it is in Java and JS.
* In JavaScript, method invocation (`myInstance.myMethod()`) is a special syntactic form like in Java that passes along `this`, but `myInstance.myMethod` is also allowed and drops `myInstance`. This is efficient if you didn't care about `this`, but can be surprising to beginners and requires more care than in other languages.
To compare these: Python and JavaScript are flexible because they allow dot syntax, i.e. methods as first-class functions. JavaScript and Java are efficient because they don't do an unnecessary allocation unless you opt into it. Python and Java are harder to misuse because they don't provide a syntax for accessing `myMethod` without `myInstance` bound to it.