我已经使用面向对象编程语言编程超过十年,但现在我正在学习JavaScript,这是我第一次遇到基于原型的继承。我倾向于通过研究好的代码来快速学习。有没有一个很好的JavaScript应用程序(或库)的例子,它正确地使用了原型继承?你能简要描述一下原型继承是如何/在哪里使用的吗,这样我就知道从哪里开始阅读了?
我已经使用面向对象编程语言编程超过十年,但现在我正在学习JavaScript,这是我第一次遇到基于原型的继承。我倾向于通过研究好的代码来快速学习。有没有一个很好的JavaScript应用程序(或库)的例子,它正确地使用了原型继承?你能简要描述一下原型继承是如何/在哪里使用的吗,这样我就知道从哪里开始阅读了?
在Javascript中添加一个基于原型的继承示例。
// Animal Class
function Animal (name, energy) {
this.name = name;
this.energy = energy;
}
Animal.prototype.eat = function (amount) {
console.log(this.name, "eating. Energy level: ", this.energy);
this.energy += amount;
console.log(this.name, "completed eating. Energy level: ", this.energy);
}
Animal.prototype.sleep = function (length) {
console.log(this.name, "sleeping. Energy level: ", this.energy);
this.energy -= 1;
console.log(this.name, "completed sleeping. Energy level: ", this.energy);
}
Animal.prototype.play = function (length) {
console.log(this.name, " playing. Energy level: ", this.energy);
this.energy -= length;
console.log(this.name, "completed playing. Energy level: ", this.energy);
}
// Dog Class
function Dog (name, energy, breed) {
Animal.call(this, name, energy);
this.breed = breed;
}
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;
Dog.prototype.bark = function () {
console.log(this.name, "barking. Energy level: ", this.energy);
this.energy -= 1;
console.log(this.name, "done barking. Energy level: ", this.energy);
}
Dog.prototype.showBreed = function () {
console.log(this.name,"'s breed is ", this.breed);
}
// Cat Class
function Cat (name, energy, male) {
Animal.call(this, name, energy);
this.male = male;
}
Cat.prototype = Object.create(Animal.prototype);
Cat.prototype.constructor = Cat;
Cat.prototype.meow = function () {
console.log(this.name, "meowing. Energy level: ", this.energy);
this.energy -= 1;
console.log(this.name, "done meowing. Energy level: ", this.energy);
}
Cat.prototype.showGender = function () {
if (this.male) {
console.log(this.name, "is male.");
} else {
console.log(this.name, "is female.");
}
}
// Instances
const charlie = new Dog("Charlie", 10, "Labrador");
charlie.bark();
charlie.showBreed();
const penny = new Cat("Penny", 8, false);
penny.meow();
penny.showGender();
ES6使用构造函数和super关键字实现继承更加简单。