是否可以将一个对象扩展为“;一个函数

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

本文关键字:函数 一个 一个对象 扩展 是否      更新时间:2023-09-26

我一直觉得在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];
};

你不能。你所能做的就是接受一个对象并返回一个函数。

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

它们也有一个内部的[[Call]]属性,当它们被调用时被调用。你不能扩展一个对象并赋予它[[Call]]属性。

然而,你可以使用ES6代理(它是非标准的,浏览器支持一般)做一些非常类似的事情。

如果您为属性提供一个名称,您可以这样做:

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) { ... }