JavaScript中类的创建

本文对比了ES6之前和现在的类与继承的实现方式,详细解析了ES6如何简化了类的定义和继承机制,使代码更加清晰、易读。

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中的类实际上并没有提供额外的功能,它们通常被描述为提供语法上的糖而不是原型和继承,因为它们提供了更干净、更优雅的语法。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值