Ví dụ về kế thừa prototype ngang theo function constructor. Liên quan đến hàm call(), sẽ có bài chi

https://js.edu.vn/7-ke-thua-prototype-ngang-va-doc.html

function Hero(name,level) {
	this.name = name;
	this.level = level;
}
function Warrior(name,level,weapon) {
	Hero.call(this, name, level);
	this.weapon = weapon;
}
function Healer(name,level,spell) {
	Hero.call(this, name, level);
	this.spell = spell;
}
Warrior.prototype = Object.create(Hero.prototype);
Healer.prototype = Object.create(Hero.prototype);
Hero.prototype.greet = function() {
	return `${this.name} says Hello`;
}
Warrior.prototype.attack = function() {
	return `${this.name} attack with ${this.weapon}`;
}
var hero1 = new Warrior('Hero 1',1, 'axe');
var hero2 = new Healer('Hero 2',1,'cure');
console.log(hero1.greet());
console.log(hero2.greet());
console.log('bbbbbbbbbbb');
console.log(hero1.attack());
console.log(hero2.attack());

Last updated

Navigation

Lionel

@Copyright 2023