• 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会总是指向实例对象。

  • 相关阅读:
    22、Flyweight 享元模式
    js随机点名器(简单)
    js随机点名器(简单)
    PHP
    PHP
    Laravel框架实现利用监听器进行sql语句记录功能
    Laravel框架实现利用监听器进行sql语句记录功能
    PhpStorm常用的一些快捷键
    PhpStorm常用的一些快捷键
    HTTP状态码汇总
  • 原文地址:https://www.cnblogs.com/chenqionghe/p/11414797.html
Copyright © 2020-2023  润新知