1.以前的创建方式
<script>
//定义类
function Hero(name, level){
this.name = name;
this.level = level;
}
//定义类的方法
Hero.prototype.greet = function(){
return `${this.name} says hello`;
}
//实例化类
const hero1 = new Hero('Tom', 100);
const hero2 = new Hero('Jerry', 50);
console.log(hero1);
console.log(hero2);
console.log(hero1.greet());
console.log(hero2.greet());
</script>

2.ES6的创建方式
<script>
class Hero{
constructor(name, level) {
this.name = name;
this.level= level;
}
greet(){
return `${this.name} says hello`;
}
}
const hero1 = new Hero('Tom', 100);
const hero2 = new Hero('Jerry', 50);
console.log(hero1);
console.log(hero2);
console.log(hero1.greet());
console.log(hero2.greet());
</script>

3. 以前的继承
<script>
function Hero(name, level){
this.name = name;
this.level = level;
}
Hero.prototype.greet = function(){
return `${this.name} says hello`;
}
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;
}
//使用call()函数不会自动将方法传递过来,需要使用Object.create()方法将原型传递
Warrior.prototype = Object.create(Hero.prototype);
Healer.prototype = Object.create(Hero.prototype);
const warrior = new Warrior('Doom', 50, 'The doom is coming!');
const healer = new Healer('Angle', 50, 'Heros never die!');
console.log(warrior);
console.log(healer);
console.log(warrior.greet());
console.log(healer.greet());
</script>

4. ES6的继承
<script>
class Hero{
constructor(name, level) {
this.name = name;
this.level = level;
}
greet(){
return `${this.name} says hello`;
}
}
class Warrior extends Hero{
constructor(name, level, weapon){
super(name, level);
this.weapon = weapon;
}
}
class Healer extends Hero{
constructor(name, level, spell){
super(name, level);
this.spell = spell;
}
}
const warrior = new Warrior('Doom', 50, 'The doom is coming!');
const healer = new Healer('Angle', 50, 'Heros never die!');
console.log(warrior);
console.log(healer);
console.log(warrior.greet());
console.log(healer.greet());
</script>

5.总结
对比以前类的操作方式,ES6中类的写法更接近于java,与其他语言的共通性更强了,代码可读性也更高了。但是JavaScript中的类实际上并没有提供额外的功能,它们通常被描述为提供语法上的糖而不是原型和继承,因为它们提供了更干净、更优雅的语法。
本文对比了ES6之前和现在的类与继承的实现方式,详细解析了ES6如何简化了类的定义和继承机制,使代码更加清晰、易读。
1269

被折叠的 条评论
为什么被折叠?



