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

后端 未结 6 2003
失恋的感觉
失恋的感觉 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:39

    Yes, it is possible if you use the __proto__ property Daniel Cassidy mentioned. The trick is to have c actually return a function that has had a attached to its prototype chain.

    function a () {
        return "foo";
    }
    
    a.b = function () {
        return "bar";
    }
    
    function c () {
        var func = function() {
            return "I am a function";
        };
        func.__proto__ = a;
        return func;
    }
    c.prototype = a;
    
    var d = new c();
    d.b(); // returns "bar"
    d(); // returns "I am a function"
    

    However, you'll need to do some more tweaking of the prototype chain if you want instanceof to return better results.

    d instanceof c // true
    d instanceof a // false
    c instanceof a // false
    

提交回复
热议问题