JavaScript继承Object.create()无法按预期工作 [英] JavaScript inheritance Object.create() not working as expected

查看:113
本文介绍了JavaScript继承Object.create()无法按预期工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有:

主对象

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

子对象:

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

继承主属性

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

var myBanana = new Bannana();

console.log( myBanana.type );

输出: undefined 。为什么这不显示fruit作为结果?

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

推荐答案


为什么这不显示水果作为结果?

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

因为你永远不会设置在新对象上输入

type 不是属性 Fruit.prototype ,以及所有 Bannana.prototype = Object.create(Fruit.prototype); 的确如此 Fruit.prototype 的属性可用于每个 Banana 实例。

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 Fruit 函数设置。但是如果你看看你的代码,无处你正在执行 Fruit !行 this.type =fruit; 永远不会被执行! 类型属性不会神奇地

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.

所以 in另外来设置原型,你必须执行 Fruit 。你必须调用构造函数(就像你在其他语言中一样(现在是ES6)通过 super ):

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";
}






在新的JavaScript版本中(ES6 / ES2015)您可以使用

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

这是做同样的事情,但隐藏在 class 易于使用的语法。

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

这篇关于JavaScript继承Object.create()无法按预期工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆