1. 简介
ES6 提供了更接近传统语言的写法,引入了 Class(类)这个概念,作为对象的模板。通过class
关键字,可以定义类。
基本上,ES6 的class
可以看作只是一个语法糖,它的绝大部分功能,ES5 都可以做到,新的class
写法只是让对象原型的写法更加清晰、更像面向对象编程的语法而已。
//ES5写法
function Point(x, y) {
this.x = x;
this.y = y;
}
Point.prototype.toString = function () {
return '(' + this.x + ', ' + this.y + ')';
};
//ES6写法
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
//不需要加上function
toString() {
return '(' + this.x + ', ' + this.y + ')';
}
}
1.1constructor 方法
constructor()
方法是类的默认方法,通过new
命令生成对象实例时,自动调用该方法。一个类必须有constructor()
方法,如果没有显式定义,一个空的constructor()
方法会被默认添加。
1.2 类的实例
生成类的实例的写法,与 ES5 完全一样,也是使用new
命令。如果没有加上new
,像函数那样调用Class
,将会报错。
1.3 属性表达式
let methodName = 'getArea';
class Square {
constructor(length) {
// ...
}
[methodName]() {
// ...
}
}
上面代码中,Square
类的方法名getArea
,是从表达式得到的
1.4 Class 表达式
与函数一样,类也可以使用表达式的形式定义
const MyClass = class Me {
};
const MyClass = class { /* ... */ };
2. 静态方法
类相当于实例的原型,所有在类中定义的方法,都会被实例继承。如果在一个方法前,加上static
关键字,就表示该方法不会被实例继承,而是直接通过类来调用,这就称为“静态方法”。
class Foo {
static classMethod() {
return 'hello';
}
}
Foo.classMethod() // 'hello'
var foo = new Foo();
foo.classMethod()
// TypeError: foo.classMethod is not a function
3. 实例属性的新写法
实例属性除了定义在constructor()
方法里面的this
上面,也可以定义在类的最顶层。
class foo {
bar = 'hello';
baz = 'world';
constructor() {
// ...
}
}