ES6 和 TypeScript 中的类,学习记录。接上一篇:JavaScript 中的类。
ES6 中的类
一、 Class 的基本语法
ES6 引入了 Class(类)这个概念作为对象的模版。通过 class
关键字可以定义类。
基本上,ES6 中的 class 可以看作只是一个语法糖,它的绝大部分功能,ES5 都可以做到,新的 class 写法只是让对象原型的写法更加清晰,更像面向对象编程的语法而已。
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
toString() {
return '(' + this.x + ',' + this.y + ')';
}
}
1. constructor
构造方法
constructor
方法是类的默认方法,通过 new
命令生成对象实例时自动调用该方法。一个类必须有 constructor
方法,如果没有显示定义,一个空的 constructor
方法会被默认添加。
类必须通过 new
来调用,否则会报错。这是它跟普通构造函数的一个主要区别。
类不存在变量提升(hoist),这一点和 ES5 完全不同。
构造方法中 this
上的属性是定义在实例上的属性,this
就是指向实例的。还有一种定义实例属性的方法,就是直接定义类的属性成员:
2. this
的指向
类的方法内部如果含有 this
,它将默认指向类的实例。但是,必须非常小心,一旦单独使用该方法,很可能会报错。
class Logger {
printName(name = 'there') {
this.print(`Hello ${
name}`);
}
print(text) {
console.log(text);
}
}
const logger = new Logger();
const {
printName } = logger;
printName(); // TypeError: Cannot read property 'print' of undefined
解决方法:
- 在构造函数中绑定
this
class Logger { constructor() { this.printName = this.printName.bind(this); } // ... }
- 使用尖头函数:箭头函数内部的
this
总是指向定义时所在的对象。class Obj { constructor() { this.getThis = () => this; } } const myObj = new Obj(); myObj.getThis() === myObj // true
- 使用
Proxy
,在获取方法的时候自动绑定this
function selfish (target) { const cache = new WeakMap(); const handler = { get (target, key) { const value = Reflect.get(target, key); if (typeof value !== 'function') { return value; } if (!cache.has(value)) { cache.set(value, value.bind(target)); } return cache.get(value); }