您可以使对象“可调用"吗? [英] Can you make an object 'callable'?

查看:61
本文介绍了您可以使对象“可调用"吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

...

obj (a, b);

推荐答案

否,但是您可以将属性添加到函数中,例如

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

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

要使"一个对象可调用,您仍然必须执行上述操作,但它看起来可能像这样:

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

然后您将只使用"func"函数而不是对象.实际上,此方法所做的只是在两个对象之间复制属性,但是...可能会有所帮助.

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.

这篇关于您可以使对象“可调用"吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆