试图获得一个新的JS类来继承原来的类'方法
Trying to get a new JS class to inherit original class' method
我正在学习一个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
原型设置为Animal
的新实例。然而,当我提交代码时,我收到一个错误,说"确保创建一个名为Penguin的新Penguin实例!"
使用此代码:
var penguin = {
name: "Pinguino"
};
您只需创建一个object类的对象。要创建Penguin
类型的企鹅,安装Penguin
类:
var penguin = new Penguin("Pinguino");
penguin.sayName();
以下是对代码的一些改进:
function Penguin(name) {
// do not copy paste re use your code
// but actually re use it by calling
// the parent constructor
Animal.call(this,name,2);
// this.name = name;
// this.numLegs = 2;
};
// set its prototype to be a new instance of Animal
// Do not create an instance of Parent to set the
// prototype part of inheritance
//Penguin.prototype = new Animal();
Penguin.prototype = Object.create(Animal.prototype);
//when overwriting prototype you will have prototype.constructor
// point to the wrong function, repair that
Penguin.prototype.constructor=Penguin;
有关构造函数函数和原型的更多信息,请点击此处。
相关文章:
- Node.js中依赖于版本的类型继承
- Vue.js继承调用父方法
- 模块化JS和原型继承
- Node.js中的继承
- 使用继承配置netzkejavascript代码(在带有参数的父类中定义js代码)
- 向扩展数组的JS集合添加对象(继承?)
- 如何从TypeScript编译中现有的AMD js类继承到AMD模块
- JS继承和原型分配
- Angular js 从一个控制器从另一个控制器继承属性
- 继承节点js
- 三.js继承模式
- JS继承和精灵错误
- Backbone.js,继承的方法
- JS继承的例子:太多的递归
- Backbone.js继承的问题
- 辞职's JS继承脚本.父类的属性被覆盖
- Js 继承的类实例未定义
- JS继承和变异原型
- JS“继承”(代码共享)机制
- 多个gulp文件,并使用require从其他gulpfiles.js继承任务