是否可以将对象“扩展”到函数中?

时间:2011-11-08 01:06:28

标签: javascript

我总是觉得有趣的是,在JavaScript中你实际上可以将函数扩展到对象中:

var order = function(x, y) {
  return x < y ? [x, y] : [y, x];
};

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

我不会声称上面有很多理由(但是,为什么不呢?);我的问题是,是否有可能做相反的事情。也就是说,我可以拥有类似的东西:

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

2 个答案:

答案 0 :(得分:3)

你不能。你可以做的是拿一个对象并返回一个函数。

记住函数是对象,除了它们继承自Function.prototype而不是Object.prototype

它们还具有内部[[Call]]属性,在调用它们时会调用它。您无法扩展对象并为其提供[[Call]]属性。

但是你可以使用ES6 proxies做一些非常相似的事情(这是非标准的,并且拥有平庸的浏览器支持)。

答案 1 :(得分:0)

如果您提供该物业的名称,您可以这样做:

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

下式给出:

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

但我不知道为什么我要这样做而不是:

order.reverse = function (x,y) { ... }
相关问题