JavaScript基于原型的继承的好例子

89

我已经使用面向对象编程语言编程超过十年,但现在我正在学习JavaScript,这是我第一次遇到基于原型的继承。我倾向于通过研究好的代码来快速学习。有没有一个很好的JavaScript应用程序(或库)的例子,它正确地使用了原型继承?你能简要描述一下原型继承是如何/在哪里使用的吗,这样我就知道从哪里开始阅读了?


1
你有机会查看那个Base库吗?它真的很好,而且非常小。如果你喜欢它,请考虑将我的答案标记为答案。谢谢,roland。 - Roland Bouman
我想我和你处于同一条船上。我也想学习一些有关原型语言的知识,不仅局限于oop框架或类似的东西,尽管它们很棒,但我们需要学习,对吧?不只是让某个框架为我所用,即使我会使用它。而是学习如何用新的方式在新的语言中创建新的东西,打破常规思维。我喜欢你的风格。我会尝试帮助自己,也许能帮到你。一旦我找到了什么,我会告诉你的。 - marcelo-ferraz
11个回答

0

在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关键字实现继承更加简单。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接