JavaScript inheritance Object.create() not working as expected

吃可爱长大的小学妹 提交于 2019-12-31 03:06:08

问题


I have:

Master object

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

Sub-object:

function Bannana() {
    this.color = "yellow";
}

Inherit master properties

Bannana.prototype = Object.create( Fruit.prototype );

var myBanana = new Bannana();

console.log( myBanana.type );

Outputs: undefined. Why is this not displaying "fruit" as the outcome?


回答1:


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.




回答2:


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?




回答3:


You never put anything on the Fruit prototype object. Your constructor initializes the instances, not the prototype.

If you had:

Fruit.prototype.type = "fruit";

then your code would work as you expect.



来源:https://stackoverflow.com/questions/30991020/javascript-inheritance-object-create-not-working-as-expected

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!