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会指向该方法运行时所在的环境,因为找不到print方法而导致报错。
class Logger {
constructor() {
//在构造方法中绑定this,这样就不会找不到print方法了。
this.printName = this.printName.bind(this);
}
// ...
}
//另一种解决方法是使用箭头函数。
class Logger {
constructor() {
this.printName = (name = 'there') => {
this.print(`Hello ${name}`);
};
}
// ...
}
es6 class this指向 (二)
最新推荐文章于 2023-02-07 18:48:06 发布