ECMAScript6: 类
来自CloudWiki
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();