一、构造对象
ES6之前,JavaScript 语言中生成实例对象的传统方法是通过构造函数,ES6提出用class来构造实例对象。
//用函数构造实例对象
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);
//ES6用class构造实例对象
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
toString() {
return '(' + this.x + ', ' + this.y + ')';
}
}
typeof Point // "function"
Point === Point.prototype.constructor // true
注意:
1、定义“类”的方法的时候,前面不需要加上function这个关键字。另外,方法之间不能用逗号分隔。
2、类的数据类型就是函数,类本身就指向构造函数。
3、实例的属性除非显式定义在其本身(上文的this对象),否则都是定义在原型上(即定义在class.prototype上),x和y是定义在实例上,toString和constructor是定义在原型上。
二、内部this的指向
类的方法内部如果含有this,它默认指向类的实例。
三、Class 的 Generator 方法
Generator返回遍历器,给class数据结构提供可遍历的接口,具体实现如下:
class Foo {
constructor(...args) {
this.args = args;
}
* [Symbol.iterator]() {
for (let arg of this.args) {
yield arg;
}
}
}
for (let x of new Foo('hello', 'world')) {
console.log(x);
}
// hello
// world
四、class中的静态方法
static关键字,表明该方法是一个静态方法,可直接在类上调用,而不是在Foo类的实例上调用,如果静态方法包含this关键字,这个this指的是类,而不是实例。另外静态方法是可继承的。
class Foo {
static bar () {
this.baz();
}
static baz () {
console.log('hello');
}
baz () {
console.log('world');
}
}
Foo.bar() // hello
五、类的继承
Class 可以通过extends关键字实现继承
class Point {
}
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方法中调用super方法,否则新建实例时会报错。这是因为子类自己的this对象,必须先通过父类的构造函数完成塑造,得到与父类同样的实例属性和方法,然后再对其进行加工,加上子类自己的实例属性和方法。若步骤有误,则会报错。另外,如果类没有定义constructor方法,这个方法会被默认添加。
- super关键词
1、super作为函数时,仅可用在构造函数中,其内部的this,将指向子类。
2、super作为对象时,在非静态方法中,指向父类的原型对象,在静态方法中,指向父类。
class A {}
A.prototype.x = 2;
class B extends A {
constructor() {
super();
console.log(super.x) // 2
}
}
let b = new B();
3、在子类普通方法中通过super调用父类的方法时,父类的方法内部的this指向当前的子类实例。
class A {
constructor() {
this.x = 1;
}
print() {
console.log(this.x);
}
}
class B extends A {
constructor() {
super();
this.x = 2;
}
m() {
super.print();
}
}
let b = new B();
b.m() // 2
3、super赋值和取值
class A {
constructor() {
this.x = 1;
}
}
class B extends A {
constructor() {
super();
this.x = 2;
super.x = 3;
console.log(super.x); // undefined
console.log(this.x); // 3
}
}
let b = new B();
- 写值:当写入super.x的时候,写的是this.x,this指向子类
- 读值:当读取super.x的时候,读的是A.prototype.x
class A {
constructor() {
this.x = 1;
}
}
class B extends A {
constructor() {
super();
this.x = 2;
super.x = 3;
console.log(super.x); // undefined
console.log(this.x); // 3
}
}
let b = new B();
另外,在子类的静态方法中通过super调用父类的方法时,方法内部的this指向当前的子类,而不是子类的实例。