JavaScript inheritance Object.create() not working as expected

后端 未结 3 402
刺人心
刺人心 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:35

    Why is this not displaying "fruit" as the outcome?

    Because you are never setting type on the new object.

    type isn't a property of Fruit.prototype, and all that Bannana.prototype = Object.create( Fruit.prototype ); does is make the properties of Fruit.prototype available to each Banana instance.

    type is set by the Fruit function. But if you look at your code, nowhere are you executing Fruit! The line this.type = "fruit"; is never executed! The type property does not magically come to existence.

    So in addition to setting the prototype, you have to execute Fruit. You have to call the parent constructor (just like you do in other languages (and ES6 now) via super):

    function Bannana() {
        Fruit.call(this); // equivalent to `super()` in other languages
        this.color = "yellow";
    }
    

    In the new JavaScript version (ES6/ES2015) you would use classes instead:

    class Banana extends Fruit {
        constructor() {
            super();
            this.color = 'yellow;
        }
    }
    

    This does the same thing, but hides it behind the class syntax for ease of use.

提交回复
热议问题