3

假设我有一个功能:

var func = function(param){return param + 1;};

鉴于函数是对象,我可以向它添加属性:

func.prop = 'foo';

两者都func(4)应该func.prop工作。但现在假设我有一个对象:

var obj = {prop: 'foo'};

...我想让它作为一个增量函数调用。这可能吗?

4

2 回答 2

6

我想让 [an Object] 作为增量函数调用。这可能吗?

不。

由 Object 构造函数创建的对象没有内部[[Call]]方法,因此无法调用。[[Call]]这是使函数成为函数的特殊方法。请注意,对象构造函数是一个函数,但它生成的是普通对象,而不是函数。

虽然 Functions 继承自Object.prototype,但它们是由 Function 构造函数创建的。内置构造函数具有 ECMA-262 赋予它们的额外权力。:-)

于 2012-11-10T03:13:17.837 回答
2

这是一个坏主意(IMO,对于蹩脚的语法糖来说这是很多开销),但可以做到。

function InvokableObject(properties) {
    var propName,
        invoke = properties.invoke,
        fn = typeof invoke === 'string' ? 
            function () {
                return fn[invoke].call(fn, arguments);
            } : 
            function () {
                return invoke.call(fn, arguments);
            };
    delete properties.invoke;
    for (propName in properties) {
        if (properties.hasOwnProperty(propName)) {
            fn[propName] = properties[propName];
        }
    }
    return fn;
}

现在,您可以指定一个函数作为“invoke”属性,当您调用该对象时,它将运行:

var incrementable = InvokableObject({
    value: 0,
    invoke: function () {
        this.value += 1;
        return this.value;
    }
});

console.log(incrementable.value); //0
console.log(incrementable()); //1
console.log(incrementable()); //2

或者,您可以指定调用函数的名称:

var incrementable = InvokableObject({
    value: 0,
    invoke: 'increment',
    increment: function () {
        this.value += 1;
        return this.value;
    }
});

console.log(incrementable.value); //0
console.log(incrementable()); //1
console.log(incrementable()); //2

不过,说真的,不要这样做。只需调用 obj.increment 或其他什么。

于 2014-10-03T17:53:08.107 回答