前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >node.js中this指向失效解决

node.js中this指向失效解决

作者头像
雪山飞猪
发布2019-08-29 14:50:03
2.1K0
发布2019-08-29 14:50:03
举报
文章被收录于专栏:雪山飞猪雪山飞猪

问题:在外部单独使用类实例对象的方法,this没有指向该类实例对象

代码如下

代码语言:javascript
复制
class CQH {
    hello() {
        let name = this.name();
        console.log(`Hello ${name}`);
    }

    name() {
        return "chenqionghe"
    }
}

const cqh = new CQH();
const hello = cqh.hello;
hello();

运行报错,找不到this

代码语言:javascript
复制
 let name = this.name();
                        ^
TypeError: Cannot read property 'name' of undefined

原因:虽然类默认的方法指向类的实例,但是如果在外部单独使用该方法,this会指向该方法运行时所在的环境,不再指向对象

解决办法

1. 显示指定bind方法指定this

可以在构造方法中绑定this

代码语言:javascript
复制
class CQH {
    constructor() {
        this.hello = this.hello.bind(this)
    }

    hello() {
        let name = this.name();
        console.log(`Hello ${name}`);
    }

    name() {
        return "chenqionghe"
    }
}

也可以在外部使用bind,例如

代码语言:javascript
复制
const cqh = new CQH();
const hello = cqh.hello.bind(cqh);

2. 使用箭头函数

代码语言:javascript
复制
class CQH {
    constructor() {
        this.hello = () => {
            let name = this.name();
            console.log(`Hello ${name}`);
        }
    }

    name() {
        return "chenqionghe"
    }
}

箭头函数内部的this总是指向定义时所在的对象,是在构造函数执行的时候,箭头函数所在的运行环境,肯定是实例对象,所以this会总是指向实例对象。

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019-08-26 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 问题:在外部单独使用类实例对象的方法,this没有指向该类实例对象
  • 解决办法
    • 1. 显示指定bind方法指定this
      • 2. 使用箭头函数
      领券
      问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档