Can a JavaScript object have a prototype chain, but also be a function?

后端 未结 6 2002
失恋的感觉
失恋的感觉 2020-11-27 19:20
function a () {
    return \"foo\";
}

a.b = function () {
    return \"bar\";
}

function c () { };
c.prototype = a;

var d = new c();
d.b(); // returns \"bar\"
d()         


        
6条回答
  •  执笔经年
    2020-11-27 19:44

    This is something I've been trying to do for a while now. Special thanks to the authors above for their input.

    Here is a chained implementation of using a "callable-object":

    var $omnifarious = (function(Schema){
    
        var fn = function f(){
            console.log('ran f!!!');
            return f;
        };
    
        Schema.prototype = {
            w: function(w){ console.log('w'); return this; },
            x: function(x){ console.log('x'); return this; },
            y: function(y){ console.log('y'); return this; }
        };
        fn.__proto__ = (new Schema()).__proto__;
    
        return fn;
    })(function schema(){ console.log('created new schema', this); });
    
    console.log(
        $omnifarious()().w().x().y()()()
    );
    

    Also, with this "Schema" approach, it may be possible to create a reusable interface using Object.freeze() on Schema's prototype or __proto__ object. That might look something like this: fn.__proto__ = Object.freeze(new Schema().__proto__) -- this is not a practical example and more may be needed. That said, its a different discussion. Try it out and let me know!

    Hope this is helpful.

提交回复
热议问题