javascript - 尝试让一个新的JS类继承原类的方法

标签 javascript object inheritance

我正在学习 JavaScript 教程,它要求我创建执行以下操作:

Create a Penguin object with the variable name penguin and any name you'd like.

Then call penguin.sayName();.

我的代码如下:

// the original Animal class and sayName method
function Animal(name, numLegs) {
    this.name = name;
    this.numLegs = numLegs;
}
Animal.prototype.sayName = function() {
    console.log("Hi my name is " + this.name);
};

// define a Penguin class
function Penguin(name) {
    this.name = name;
    this.numLegs = 2;
};

// set its prototype to be a new instance of Animal
Penguin.prototype = new Animal();

// Here's where I need to create the Penguin object
var penguin = {
    name: "Pinguino"
};

penguin.sayName(name);

我相当确定我的代码在将 Penguin 原型(prototype)设置为 Animal 的新实例时是正确的。然而,当我提交代码时,我收到一条错误消息“确保创建一个名为 penguin 的新 Penguin 实例!”

最佳答案

使用此代码:

var penguin = {
    name: "Pinguino"
};

您只需创建一个 Object 类的对象。 要创建 Penguin 类型的企鹅,实例化 Penguin 类:

var penguin = new Penguin("Pinguino");
penguin.sayName();

关于javascript - 尝试让一个新的JS类继承原类的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26245289/

相关文章:

java - 如何在另一个对象上使用一个对象的实例变量java

c++ - C++中获取特定函数名的字符串

c# - 静态接口(interface)等效 C#

hibernate - 使用 Spring Data JPA 的连接继承时避免跨表的外部连接

javascript - 当纬度和经度点数量很大时,谷歌地图无法正确绘制

Javascript (ECMA-6) 类魔术方法 __call 像 PHP

Javascript Parse SDK 节省两倍

javascript - 装饰器或子类化是 React.Component 的最佳模式

javascript - 在 ipad 上触发 unhover/mouseout/blur

javascript - RxJS Node 在订阅下一个序列之前等待 observable 完成