ES6 中的类实际上就是个函数,而且正如函数的定义方式有函数声明和函数表达式两种一样,类的定义方式也有两种,分别是:类声明、类表达式。
类声明
类声明是定义类的一种方式,就像下面这样,使用 class 关键字后跟一个类名(这里是 Ploygon),就可以定义一个类。
'use strict';
class Polygon {
constructor(height, width) {
this.height = height;
this.width = width;
}
}变量提升
类声明和函数声明不同的一点是,函数声明存在变量提升现象,而类声明不会。也就是说,你必须先声明类,然后才能使用它,否则代码会抛出 ——ReferenceError 异常,像下面这样:
var p = new Polygon(); // ReferenceError
class Polygon {}声明一个类,命名为(Person),构造函数(constructor)中定义name属性。
'use strict';
class Polygon {
constructor(name) {
this.name = name;
}
}
var p = new Polygon('聂峰军');
console.log('姓名:' p.name);类表达式是定义类的另外一种方式,就像函数表达式一样,在类表达式中,类名是可有可无的。如果定义了类名,则该类名只有在类体内部才能访问到。
'use strict';
// 匿名类表达式
var Polygon = class {
constructor(height, width) {
this.height = height;
this.width = width;
}
};
// 命名类表达式
var Polygon = class Polygon {
constructor(height, width) {
this.height = height;
this.width = width;
}
};类的成员需要定义在一对花括号 {} 里,花括号里的代码和花括号本身组成了类体。类成员包括类构造器和类方法(包括静态方法和实例方法)。
class 根据 constructor 方法来创建和初始化对象。
constructor方法是类的默认方法,通过new命令生成对象实例时,自动调用该方法。一个类只能有一个constructor方法,如果没有显式定义,一个空的constructor方法会被默认添加。
constructor() {}constructor方法默认返回实例对象(即this),完全可以指定返回另外一个对象。
'use strict';class Foo {
constructor() {
return Object.create(null);
}
}
new Foo() instanceof Foo
// false上面代码中,constructor函数返回一个全新的对象,结果导致实例对象不是Foo类的实例。
constructor 方法是一个特殊的类方法,它既不是静态方法也不是实例方法,它仅在实例化一个类的时候被调用。一个类只能拥有一个名为 constructor 的方法,否则会抛出 SyntaxError 异常。
严格模式
类和模块的内部,默认就是严格模式,所以不需要使用use strict指定运行模式。只要你的代码写在类或模块之中,就只有严格模式可用。
static关键字定义了一个类的静态方法。静态方法被称为无需实例化类也可当类被实例化。静态方法通常用于为应用程序创建实用函数。
'use strict';
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));extends 关键字可以用来创建继承于某个类的子类。
这个例子是根据名为Animal类创建一个名为niefengjun的类。
'use strict';
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(this.name ' makes a noise.');
}
}
class niefengjun extends Animal {
speak() {
console.log(this.name ' 你好.');
}
}
var nie = new niefengjun('niefengjun.cn');
nie.speak();执行结果
kevie:dianying tom$ node nodeinfo.js niefengjun.cn 你好.
