Dan Tao
Dan Tao

Reputation: 128327

Is it possible to extend an object "into" a function?

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];
};

Upvotes: 0

Views: 97

Answers (2)

RobG
RobG

Reputation: 147383

If you supply a name for the property you could do:

addFunctionBehavior(order, 'reverse', function(x, y) {
    return x < y ? [x, y] : [y, x];
};

given:

function addFunctionBehavior(o, name, fn) {
  o[name] = fn;
} 

But I don't know why I'd want to do that instead of:

order.reverse = function (x,y) { ... }

Upvotes: 0

Raynos
Raynos

Reputation: 169391

You can't. What you can do is take an object and return a function.

Remember functions are objects, except they inherit from Function.prototype instead of Object.prototype

They 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).

Upvotes: 3

Related Questions