I’ve always found it interesting that in JavaScript you can actually extend functions into objects:
var order = function(x, y) {
return x < y ? [x, y] : [y, x];
};
order.backwards = function(x, y) {
return order(x, y).reverse();
};
I won’t claim there is much reason to do the above (but then again, why not?); my question is simply whether it’s possible to do the opposite. That is, could I have something like:
var order = {
backwards: function(x, y) {
return order(x, y).reverse();
}
};
// Obviously, this is not real; I'm just wondering if there's any way
// to accomplish the same thing.
addFunctionBehavior(order, function(x, y) {
return x < y ? [x, y] : [y, x];
};
You can’t. What you can do is take an object and return a function.
Remember functions are objects, except they inherit from
Function.prototypeinstead ofObject.prototypeThey also have an internal
[[Call]]property that is invoked when they are invoked. you can’t extend an object and give it a[[Call]]property.However you would be able to do something very similar using ES6 proxies (which are non-standard and have mediocre browser support).