class in ES6

在es6出来之后,我们看到js终于有class这个关键字,表示我们终于可以使用官方的类了。那么es6的类和之前的我们使用原型链继承实现的类有什么联系么。

答案是一模一样

JavaScript classes introduced in ECMAScript 2015 are syntactical sugar over JavaScript’s existing prototype-based inheritance. (在 ECMAScript 6 引入的 JavaScript 类(class)是 JavaScript 现有的原型继承的语法糖。) —— MDN Classes

好吧,那么为了使我们更好的理解es6的class,也是倒过来更好的理解js的原型链,下面我们把类的es6写法和原型链实现的写法一一列出

###类的创建,类的构造器和原型方法
ES6

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Polygon {
constructor(height, width) {
this.height = height;
this.width = width;
}

calcArea() {
return this.height * this.width;
}
}
const square = new Polygon(10, 10);

// 100
console.log(square.area);

原型链

1
2
3
4
5
6
7
8
var Polygon = function(height, width){
this.height = height;
this.width = width;
}

Polygon.prototype.calcArea = function() {
return this.height * this.width;
}

###类的静态方法
static关键字用来定义类的静态方法。静态方法是指那些不需要对类进行实例化),使用类名就可以直接访问的方法,需要注意的是静态方法不能被实例化的对象调用。静态方法经常用来作为工具函数。
ES6

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}

static distance(a, b) {
const dx = a.x - b.x;
const dy = a.y - b.y;

return Math.sqrt(dx*dx + dy*dy);
}
}

const p1 = new Point(5, 5);
const p2 = new Point(10, 10);

console.log(Point.distance(p1, p2));

原型链

1
2
3
4
5
6
7
8
9
10
11
var Point = function(x, y){
this.x = x;
this.y = y;
}

Point.distance = function(a, b) {
const dx = a.x - b.x;
const dy = a.y - b.y;

return Math.sqrt(dx*dx + dy*dy);
}

至此我们也可以明白了如何用原型链去构建一个类

其实当我们去查看babel对于类的实现,其实也是一样的

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
var _createClass = function() {
function defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
return function(Constructor, protoProps, staticProps) {
//实例方法(原型方法)的实现
if (protoProps) defineProperties(Constructor.prototype, protoProps);
//静态函数的实现
if (staticProps) defineProperties(Constructor, staticProps);
return Constructor;
};
}();

###类的继承

未完

参考文档
Javascript原型链
MDN Classes