JavaScript语言的传统方法是通过构造函数,定义并生成新对象。下面是一个例子。
function Point(x, y) { this.x = x; this.y = y; } Point.prototype.toString = function () { return this.x + this.y; }; var p = new Point(1, 2); p.toString()//3
class
//定义类 class Point { constructor(x, y) { this.x = x; this.y = y; } toString() { return this.x + this.y; } } let pointC=new Point(1,3); pointC.toString(); //todo typeof Point //function Point===Point.prototype.constructor //true
constructor方法
constructor
方法是类的默认方法,通过new
命令生成对象实例时,自动调用该方法。一个类必须有constructor
方法,如果没有显式定义,一个空的constructor
方法会被默认添加
constructor() {}
不存在变量提升
Class不存在变量提升
new Foo(); // ReferenceError class Foo {}
Class的继承
基本用法
Class之间可以通过extends
关键字实现继承,这比ES5的通过修改原型链实现继承,要清晰和方便很多。
class ColorPoint extends Point { constructor(x, y, color) { super(x, y); // 调用父类的constructor(x, y) 父类构造函数的参数 this.color = color; } toString() { return this.color + ' ' + super.toString(); // 调用父类的toString() } }
constructor
方法和toString
方法之中,都出现了super
关键字,它在这里表示父类的构造函数,用来新建父类的this
对象。
子类必须在constructor
方法中调用super
方法,否则新建实例时会报错。这是因为子类没有自己的this
对象,而是继承父类的this
对象,然后对其进行加工。如果不调用super
方法,子类就得不到this
对象。
class Point { /* ... */ } class ColorPoint extends Point { constructor() { } } let cp = new ColorPoint(); // ReferenceError
ColorPoint
继承了父类Point
,但是它的构造函数没有调用super
方法,导致新建实例时报错。
在子类的构造函数中,只有调用super
之后,才可以使用this
关键字,否则会报错。这是因为子类实例的构建,是基于对父类实例加工,只有super
方法才能返回父类实例
class Point { constructor(x, y) { this.x = x; this.y = y; } } class ColorPoint extends Point { constructor(x, y, color) { this.color = color; // ReferenceError super(x, y); this.color = color; // 正确 } }