ECMAScript6: 类

来自CloudWiki
Cloud17讨论 | 贡献2021年1月31日 (日) 08:00的版本 (创建页面,内容为“ES引入了class的概念,新的class写法让对象原型的写法更加清晰 ==定义类== <nowiki> class Car{ // 等价于Car构造函数 constructor(sColo…”)
(差异) ←上一版本 | 最后版本 (差异) | 下一版本→ (差异)
跳转至: 导航搜索

ES引入了class的概念,新的class写法让对象原型的写法更加清晰

定义类

class Car{
	// 等价于Car构造函数
	constructor(sColor,iDoors){
		this.color= sColor; 
		this.doors= iDoors;
	}
	// 等价于Car.prototype.showColor
	showColor(){
		console.log(this.color);
	}
}

let oCar = new Car("red",4);
oCar.showColor();

与函数一样,类也可以使用表达式的形式定义:

let Car = class {
	// 等价于Car构造函数
	constructor(sColor,iDoors){
		this.color= sColor; 
		this.doors= iDoors;
	}
	// 等价于Car.prototype.showColor
	showColor(){
		console.log(this.color);
	}
}

let oCar = new Car("red",4);
oCar.showColor();

使用类表达式,可以立即调用类构造函数从而构建一共类的单例对象:

let car = new class {
	// 等价于Car构造函数
	constructor(sColor,iDoors){
		this.color= sColor; 
		this.doors= iDoors;
	}
	// 等价于Car.prototype.showColor
	showColor(){
		console.log(this.color);
	}
}("red", 4);

car.showColor();

访问器属性