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

调试界面:

输出:

相关推荐
U.2 SSD4 分钟前
ECharts漏斗图示例
前端·javascript·echarts
江城开朗的豌豆4 分钟前
我的小程序登录优化记:从短信验证到“一键获取”手机号
前端·javascript·微信小程序
excel7 分钟前
Vue Mixin 全解析:概念、使用与源码
前端·javascript·vue.js
IT_陈寒14 分钟前
Java性能优化:这5个Spring Boot隐藏技巧让你的应用提速40%
前端·人工智能·后端
勇往直前plus32 分钟前
CentOS 7 环境下 RabbitMQ 的部署与 Web 管理界面基本使用指南
前端·docker·centos·rabbitmq
北海-cherish6 小时前
vue中的 watchEffect、watchAsyncEffect、watchPostEffect的区别
前端·javascript·vue.js
2501_915909067 小时前
HTML5 与 HTTPS,页面能力、必要性、常见问题与实战排查
前端·ios·小程序·https·uni-app·iphone·html5
white-persist8 小时前
Python实例方法与Python类的构造方法全解析
开发语言·前端·python·原型模式
新中地GIS开发老师9 小时前
Cesium 军事标绘入门:用 Cesium-Plot-JS 快速实现标绘功能
前端·javascript·arcgis·cesium·gis开发·地理信息科学
Superxpang9 小时前
前端性能优化
前端·javascript·vue.js·性能优化