Can you make an object 'callable'?

前端 未结 4 542
粉色の甜心
粉色の甜心 2020-12-03 04:37

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         


        
相关标签:
4条回答
  • 2020-12-03 04:58

    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.

    0 讨论(0)
  • 2020-12-03 04:58

    ES6 has 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.

    See also: How to extend Function with ES6 classes?

    0 讨论(0)
  • 2020-12-03 05:17

    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.

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

    0 讨论(0)
  • 2020-12-03 05:18

    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.

    Object.assign(func, obj);
    Object.setPrototypeOf(func, Object.getPrototypeOf(obj));
    
    0 讨论(0)
提交回复
热议问题