JavaScript inheritance Object.create() not working as expected

后端 未结 3 361
刺人心
刺人心 2021-01-21 18:45

I have:

Master object

function Fruit() {
    this.type = \"fruit\";
}

Sub-object:

function Bannana() {
    this.color =         


        
3条回答
  •  生来不讨喜
    2021-01-21 19:26

    This is so cool. If you go this way:

    function Fruit() {
        this.type = "fruit";
    }
    function Bannana() {        
        this.color = "yellow";
    }
    Bannana.prototype =  new Fruit;
    Bannana.prototype.type='flower';
    var myBanana = new Bannana();
    console.log( myBanana.type );
    

    you will get a "flower", but if you go this way:

    function Fruit() {
        this.type = "fruit";
    }
    function Bannana() {
        Fruit.call(this);
        this.color = "yellow";
    }
    Bannana.prototype.type='flower';
    var myBanana = new Bannana();
    console.log( myBanana.type );
    

    You will get a "fruit";

    I believe no explanation needed, right?

提交回复
热议问题