JavaScript inheritance and the constructor property

前端 未结 3 1169
庸人自扰
庸人自扰 2020-11-22 01:19

Consider the following code.

function a() {}
function b() {}
function c() {}

b.prototype = new a();
c.prototype = new b();

console.log((new a()).constructo         


        
3条回答
  •  面向向阳花
    2020-11-22 01:55

    By default,

    function b() {}
    

    then b.prototype has a .constructor property which is set to b automatically. However, you're currently overwriting the prototype and thus discarding that variable:

    b.prototype = new a;
    

    Then b.prototype does not have a .constructor property anymore; it was erased with the overwrite. It does inherit from a though, and (new a).constructor === a, and hence (new b).constructor === a (it is referring to the same property in the prototype chain).

    Best to do is to simply setting it manually afterwards:

    b.prototype.constructor = b;
    

    You could also make a little function for this:

    function inherit(what, from) {
        what.prototype = new from;
        what.prototype.constructor = what;
    }
    

    http://jsfiddle.net/79xTg/5/

提交回复
热议问题