node.js中this指向失效解决

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

代码如下

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

    name() {
        return "chenqionghe"
    }
}

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

运行报错,找不到this

 let name = this.name();
                        ^
TypeError: Cannot read property 'name' of undefined

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

解决办法

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

可以在构造方法中绑定this

class CQH {
    constructor() {
        this.hello = this.hello.bind(this)
    }

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

    name() {
        return "chenqionghe"
    }
}

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

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

2. 使用箭头函数

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

    name() {
        return "chenqionghe"
    }
}

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

posted @ 2019-08-26 20:42  雪山飞猪  阅读(1137)  评论(0编辑  收藏  举报