今天把es6中的class进行了整理,
function Car () {
this.fuel = 0;
this.distance = 0;
}
Car.prototype.move = function () {
if (this.fuel < 1) {
throw new RangeError('Fuel tank is depleted')
}
this.fuel--
this.distance += 2
}
Car.prototype.addFuel = function () {
if (this.fuel >= 60) {
throw new RangeError('Fuel tank is full')
}
this.fuel++
}
相当于
class Car {
constructor () {
this.fuel = 0
this.distance = 0
}
move () {
if (this.fuel < 1) {
throw new RangeError('Fuel tank is depleted')
}
this.fuel--
this.distance += 2
}
addFuel () {
if (this.fuel >= 60) {
throw new RangeError('Fuel tank is full')
}
this.fuel++
}
}
//注意中间没有逗号。
同样也增加了继承
class Tesla extends Car {
move () {
super.move()
this.distance += 4
}
}
静态方法
class Car {
constructor () {
this.topSpeed = Math.random()
}
static isFaster (left, right) {
return left.topSpeed > right.topSpeed;
}
}
var a = new Car();
var b = new Car();
console.log(Car.isFaster(a,b));
类的prototype属性和proto属性
大多数浏览器的ES5实现之中,每一个对象都有proto属性,指向对应的构造函数的prototype属性。Class作为构造函数的语法糖,同时有prototype属性和proto属性,因此同时存在两条继承链。
(1)子类的proto属性,表示构造函数的继承,总是指向父类。
(2)子类prototype属性的proto属性,表示方法的继承,总是指向父类的prototype属性。
class A {}
class B extends A {}
B.__proto__ === A // true
B.prototype.__proto__ === A.prototype // true