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

调试界面:

输出:

相关推荐
东东5161 小时前
基于ssm的网上房屋中介管理系统vue
前端·javascript·vue.js
harrain2 小时前
什么!vue3.4开始,v-model不能用在prop上
前端·javascript·vue.js
fanruitian8 小时前
uniapp android开发 测试板本与发行版本
前端·javascript·uni-app
rayufo8 小时前
【工具】列出指定文件夹下所有的目录和文件
开发语言·前端·python
RANCE_atttackkk8 小时前
[Java]实现使用邮箱找回密码的功能
java·开发语言·前端·spring boot·intellij-idea·idea
2501_944525549 小时前
Flutter for OpenHarmony 个人理财管理App实战 - 支出分析页面
android·开发语言·前端·javascript·flutter
李白你好10 小时前
Burp Suite插件用于自动检测Web应用程序中的未授权访问漏洞
前端
刘一说11 小时前
Vue 组件不必要的重新渲染问题解析:为什么子组件总在“无故”刷新?
前端·javascript·vue.js
徐同保12 小时前
React useRef 完全指南:在异步回调中访问最新的 props/state引言
前端·javascript·react.js
刘一说12 小时前
Vue 导航守卫未生效问题解析:为什么路由守卫不执行或逻辑失效?
前端·javascript·vue.js