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
Can you make an object 'callable'?
提问by Septagram
Is it possible to make an object callable by implementing either call
or apply
on it, or in some other way? E.g.:
是否可以通过实现call
或apply
在对象上或以其他方式使对象可调用?例如:
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
ES6
has better solution for this now. If you create your objects in a different way (using class
, extend
ing 'Function' type), you can have a callable instance of it.
ES6
现在有更好的解决方案。如果您以不同的方式创建您的对象(使用class
, extend
ing '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 Object
to pass all properties and prototype of an object obj
to 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 邮件列表建议了这一点。那个时候这个想法并没有走得太远,但也许一些额外的兴趣会帮助这个想法再次动起来。