先上代码:
正常运行的代码:
javascript
class Logger{
printName(name = 'kexuexiong'){
this.print(`hello ${name}`);
}
print(text){
console.log(text);
}
}
const logger = new Logger();
logger.printName("kexueixong xiong");
输出:
单独调用函数printName:
javascript
class Logger{
printName(name = 'kexuexiong'){
this.print(`hello ${name}`);
}
print(text){
console.log(text);
}
}
const logger = new Logger();
const {printName} = logger;
printName("kexueixong xiong");
输出:
debugger调试一下,看看什么情况,调试代码:
javascript
class Logger{
printName(name = 'kexuexiong'){
this.print(`hello ${name}`);
}
print(text){
console.log(text);
}
}
const logger = new Logger();
const {printName} = logger;
debugger;
printName("kexueixong xiong");
调试界面,this显示undefined,在单独调用时,this的指向是undefined。在单独调用的场景下,要如何才能解决该问题呢?下面给出两种种比较简单的解决方法。
1、在构造方法中绑定this,这样就不会找不到print方法了
javascript
class Logger {
constructor() {
this.printName = this.printName.bind(this);//bind函数绑定this对象
}
printName(name = 'kexuexiong') {
debugger;
this.print(`hello ${name}`);
}
print(text) {
console.log(text);
}
}
const logger = new Logger();
const { printName } = logger;
printName("kexueixong xiong");
调试界面,显示绑定了this。
输出:
2、解决方法是使用箭头函数
因为箭头函数有固话this的作用。
javascript
class Logger {
constructor() {
this.printName = this.printName.bind(this);//bind函数绑定this对象
}
//使用箭头函数固化this
printName =(name = 'kexuexiong') => {
debugger;
this.print(`hello ${name}`);
};
print(text) {
console.log(text);
}
}
const logger = new Logger();
const { printName } = logger;
printName("kexueixong xiong");
调试界面:
输出: