先上代碼:
正常運(yùn)行的代碼:
class Logger{
printName(name = 'kexuexiong'){
this.print(`hello ${name}`);
}
print(text){
console.log(text);
}
}
const logger = new Logger();
logger.printName("kexueixong xiong");
輸出:
單獨(dú)調(diào)用函數(shù)printName:
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調(diào)試一下,看看什么情況,調(diào)試代碼:
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");
調(diào)試界面,this顯示undefined,在單獨(dú)調(diào)用時(shí),this的指向是undefined。在單獨(dú)調(diào)用的場(chǎng)景下,要如何才能解決該問(wèn)題呢?下面給出兩種種比較簡(jiǎn)單的解決方法。
1、在構(gòu)造方法中綁定this,這樣就不會(huì)找不到print方法了
class Logger {
constructor() {
this.printName = this.printName.bind(this);//bind函數(shù)綁定this對(duì)象
}
printName(name = 'kexuexiong') {
debugger;
this.print(`hello ${name}`);
}
print(text) {
console.log(text);
}
}
const logger = new Logger();
const { printName } = logger;
printName("kexueixong xiong");
調(diào)試界面,顯示綁定了this。
輸出:
2、解決方法是使用箭頭函數(shù)
因?yàn)榧^函數(shù)有固話this的作用。文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-705851.html
class Logger {
constructor() {
this.printName = this.printName.bind(this);//bind函數(shù)綁定this對(duì)象
}
//使用箭頭函數(shù)固化this
printName =(name = 'kexuexiong') => {
debugger;
this.print(`hello ${name}`);
};
print(text) {
console.log(text);
}
}
const logger = new Logger();
const { printName } = logger;
printName("kexueixong xiong");
調(diào)試界面:
輸出:文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-705851.html
到了這里,關(guān)于【ES6】Class中this指向的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!