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

调试界面:

输出:

相关推荐
阿芯爱编程4 小时前
2025前端面试题
前端·面试
前端小趴菜055 小时前
React - createPortal
前端·vue.js·react.js
晓13135 小时前
JavaScript加强篇——第四章 日期对象与DOM节点(基础)
开发语言·前端·javascript
菜包eo6 小时前
如何设置直播间的观看门槛,让直播间安全有效地运行?
前端·安全·音视频
烛阴6 小时前
JavaScript函数参数完全指南:从基础到高级技巧,一网打尽!
前端·javascript
chao_7897 小时前
frame 与新窗口切换操作【selenium 】
前端·javascript·css·selenium·测试工具·自动化·html
天蓝色的鱼鱼7 小时前
从零实现浏览器摄像头控制与视频录制:基于原生 JavaScript 的完整指南
前端·javascript
三原8 小时前
7000块帮朋友做了2个小程序加一个后台管理系统,值不值?
前端·vue.js·微信小程序
popoxf8 小时前
在新版本的微信开发者工具中使用npm包
前端·npm·node.js
爱编程的喵8 小时前
React Router Dom 初步:从传统路由到现代前端导航
前端·react.js