【ES6】Class中this指向

先上代码:

正常运行的代码:

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");

调试界面:

输出:

相关推荐
灵感__idea7 小时前
Hello 算法:贪心的世界
前端·javascript·算法
GreenTea8 小时前
一文搞懂Harness Engineering与Meta-Harness
前端·人工智能·后端
killerbasd10 小时前
牧苏苏传 我不装了 4/7
前端·javascript·vue.js
吴声子夜歌10 小时前
ES6——二进制数组详解
前端·ecmascript·es6
码事漫谈11 小时前
手把手带你部署本地模型,让你Token自由(小白专属)
前端·后端
ZC跨境爬虫11 小时前
【爬虫实战对比】Requests vs Scrapy 笔趣阁小说爬虫,从单线程到高效并发的全方位升级
前端·爬虫·scrapy·html
爱上好庆祝11 小时前
svg图片
前端·css·学习·html·css3
王夏奇11 小时前
python中的__all__ 具体用法
java·前端·python
大家的林语冰12 小时前
《前端周刊》尤大开源 Vite+ 全家桶,前端工业革命启动;尤大爆料 Void 云服务新产品,Vite 进军全栈开发;ECMA 源码映射规范......
前端·javascript·vue.js
jiayong2312 小时前
第 8 课:开始引入组合式函数
前端·javascript·学习