javascript 你能让一个对象“可调用”吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19335983/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 15:13:23  来源:igfitidea点击:

Can you make an object 'callable'?

javascript

提问by Septagram

Is it possible to make an object callable by implementing either callor applyon it, or in some other way? E.g.:

是否可以通过实现callapply在对象上或以其他方式使对象可调用?例如:

var obj = {};
obj.call = function (context, arg1, arg2, ...) {
    ...
};

...

obj (a, b);

采纳答案by Max

No, but you can add properties onto a function, e.g.

不,但您可以向函数添加属性,例如

function foo(){}
foo.myProperty = "whatever";

EDIT: to "make" an object callable, you'll still have to do the above, but it might look something like:

编辑:要“制作”一个可调用的对象,您仍然必须执行上述操作,但它可能看起来像:

// Augments func with object's properties
function makeCallable(object, func){
    for(var prop in object){
        if(object.hasOwnProperty(prop)){
            func[prop] = object[prop];
        }
    }
}

And then you'd just use the "func" function instead of the object. Really all this method does is copy properties between two objects, but...it might help you.

然后你只需使用“func”函数而不是对象。实际上,此方法所做的只是在两个对象之间复制属性,但是……它可能对您有所帮助。

回答by 0xc0de

ES6has better solution for this now. If you create your objects in a different way (using class, extending 'Function' type), you can have a callable instance of it.

ES6现在有更好的解决方案。如果您以不同的方式创建您的对象(使用class, extending 'Function' 类型),您可以拥有它的一个可调用实例。

See also: How to extend Function with ES6 classes?

另请参阅:如何使用 ES6 类扩展函数?

回答by Rodrigo Rodrigues

Following the same line of @Max, but using ES6 extensions to Objectto pass all properties and prototype of an object objto the callable func.

遵循@Max 的同一行,但使用 ES6 扩展将Object对象的所有属性和原型传递obj给 callable func

Object.assign(func, obj);
Object.setPrototypeOf(func, Object.getPrototypeOf(obj));

回答by Brasten Sager

Others have provided the current answer ("no") and some workarounds. As far as first-class support in the future, I suggested this very thing to the es-discuss mailing list. The idea did not get very far that time around, but perhaps some additional interest would help get the idea moving again.

其他人提供了当前的答案(“否”)和一些解决方法。就未来的一流支持而言,我向 es-discuss 邮件列表建议了这一点。那个时候这个想法并没有走得太远,但也许一些额外的兴趣会帮助这个想法再次动起来。

https://esdiscuss.org/topic/proposal-default-object-method

https://esdiscuss.org/topic/proposal-default-object-method