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

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

    Actually, it turns out that this is possible, albeit in a non-standard way.

    Mozilla, Webkit, Blink/V8, Rhino and ActionScript provide a non-standard __proto__ property, which allow changing the prototype of an object after it has been created. On these platforms, the following code is possible:

    function a () {
        return "foo";
    }
    
    a.b = function () {
        return "bar";
    }
    
    function c () {
        return "hatstand";
    }
    c.__proto__ = a;
    
    c(); // returns "hatstand"
    c.b(); // returns "bar"; inherited from a
    

    This might be of use to anyone who doesn't need to worry about cross-platform compatibility.

    However, note that only the properties of an object can be inherited. For example:

    var d = {};
    d.__proto__ = a;
    d.b(); // returns "bar"
    d(); // throws exception -- the fact that d is inheriting from a function
         // doesn't make d itself a function.
    

提交回复
热议问题