zoukankan      html  css  js  c++  java
  • 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会总是指向实例对象。

  • 相关阅读:
    全文本搜索神器
    唯一索引和普通索引怎么选择
    程序员应不应该搞全栈
    c 的陷阱
    抽象能力
    电影电视剧推荐
    系统故障诊断
    一次web网站被入侵的处理记录
    Spark RDD 操作
    (转)Mysql哪些字段适合建立索引
  • 原文地址:https://www.cnblogs.com/chenqionghe/p/11414797.html
Copyright © 2011-2022 走看看