If this is the most important feature, then how unfortunate is it that “functions as objects” is so badly broken in Javascript?
In many other languages, functions are actually first class objects on their own, no matter where they come from. Unfortunately, due to Javascript’s… ah… idiosyncratic this
variable, Javascript methods are not actually objects.
Here’s a common Python idiom.
# A
result = object.method(data)# B
saved_method = object.method# ... perhaps much later ...result = saved_method(data)
In other words, you can just pull off any method from an object and use it as if it were a free function. Very similar techniques are possible in many other scripting languages.
And this is very useful, particularly for using methods as callbacks, and completely intuitive.
But compare and contrast to Javascript…
# A
var result = object.method(data);# B
var saved_method = object.method;# ... perhaps much latervar WRONG_result = saved_method(data);
var correct_result = saved_method.call(object, data);
In Javascript, you cannot in general pull a method off an object. To correctly call the method, you need the method function and the original object the method was written on!
Yes, if you are the one writing the object, then you can structure your Javascript so that WRONG_result
does actually work. But then that technique will only work on objects that you have written or that you know personally are designed this way.
This is a trap. You get into the habit of pulling off methods, and one day you pull off a method from a classic object, and you are burnt. Worse, it might work in your codebase right now — because this
happens to have the right value whenever the method gets called — and fail later, when the method is called from the “wrong” place in your program.
I think Javascript is a more elegant language than people give it credit for — but this isn’t one of those elegant bits.