การเพิ่มตัวอย่างของ Prototype based inheritance ใน Javascript
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);
}
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);
}
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.");
}
}
const charlie = new Dog("Charlie", 10, "Labrador");
charlie.bark();
charlie.showBreed();
const penny = new Cat("Penny", 8, false);
penny.meow();
penny.showGender();
ES6 ใช้การใช้งานการสืบทอดที่ง่ายกว่ามากโดยใช้ตัวสร้างและคำหลักขั้นสูง