Javascript 尝试获取一个新的JS类来继承原始类';方法
我正在学习JavaScript教程,它要求我创建并执行以下操作:Javascript 尝试获取一个新的JS类来继承原始类';方法,javascript,object,inheritance,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 =
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的新Penguin实例!”:
var penguin = {
name: "Pinguino"
};
您只需创建一个类object的对象。
要创建类型为penguin
,instanciatepenguin
类的企鹅,请执行以下操作:
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;
有关构造函数和原型的更多信息。Aah。非常感谢。我知道我离得很近,但我就是不能完全理解。我仍然记不住所有的单词。如果我能投你一票,我会的,但很明显,我没有足够的声誉。没问题。我很高兴你现在理解了对象实例化。谢谢你。我对JS仍然非常基础,所以希望在我继续学习的过程中,我将学习更多的方法以更有效的方式编写相同的代码。