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

调试界面:

输出:

相关推荐
fruge24 分钟前
Vue项目中的Electron桌面应用开发实践指南
前端·vue.js·electron
漂流瓶jz6 小时前
Webpack中各种devtool配置的含义与SourceMap生成逻辑
前端·javascript·webpack
前端架构师-老李6 小时前
React 中 useCallback 的基本使用和原理解析
前端·react.js·前端框架
木易 士心7 小时前
CSS 中 `data-status` 的使用详解
前端·css
明月与玄武7 小时前
前端缓存战争:回车与刷新按钮的终极对决!
前端·缓存·回车 vs 点击刷新
牧马少女7 小时前
css 画一个圆角渐变色边框
前端·css
zy happy7 小时前
RuoyiApp 在vuex,state存储nickname vue2
前端·javascript·小程序·uni-app·vue·ruoyi
小雨青年8 小时前
Cursor 项目实战:AI播客策划助手(二)—— 多轮交互打磨播客文案的技术实现与实践
前端·人工智能·状态模式·交互
小光学长8 小时前
基于Vue的儿童手工创意店管理系统as8celp7(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面。
前端·数据库·vue.js
meichaoWen8 小时前
【Vue】Vue框架的基础知识强化
前端·javascript·vue.js