javascript - 对象原型(prototype)和继承

标签 javascript prototypal-inheritance

// 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() {
    this.name = "penguin";
    this.numLegs = 2;
}

// set its prototype to be a new instance of Animal
var penguin = new Animal("Penguin", 2);

penguin.sayName();

编译器要求我“创建一个名为 penguin 的新 Penguin 实例”...

不确定我在这里做错了什么

最佳答案

以下是如何使用 JavaScript 中的原型(prototype)继承创建一个继承自 Animal 的 Penguin 对象:

// 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() {
    this.name = "penguin";
    this.numLegs = 2;
}
// set its prototype to be a new instance of Animal
Penguin.prototype = new Animal();


// Create new Penguin
var penguin = new Penguin();

penguin.sayName(); // outputs "Hi my name is penguin"
var legCount = penguin.numLegs; // outputs 2

这里有一篇文章详细解释了 JavaScript 原型(prototype)继承: http://pietschsoft.com/post/2008/09/JavaScript-Prototypal-Inheritence-Explained-in-Simple-Terms

关于javascript - 对象原型(prototype)和继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28787945/

相关文章:

Javascript:如果不用定义原型(prototype)方法也能实现继承,为什么还要使用定义原型(prototype)方法来继承?

javascript - 为什么我们在 JS 面向对象编程中使用 Prototype

Javascript 原型(prototype) : Replacement vs Addition

javascript - 使用自定义复选框,在其更改的事件上调用函数

javascript - Node.js (Openshift) 快速响应不起作用

javascript - 如何进行搜索以搜索静态网站中的 html 文件,而不管任何页面搜索栏位于

JavaScript 扩展类型返回

javascript - Angular js - 单击按钮将数据添加到现有模型

javascript - 表单提交仅在第二次点击时提交,需要在 ES6 中回调

javascript - 克隆或应用 : which is "better"?