【问题标题】:this is undefined in class这是在类中未定义的
【发布时间】:2018-10-26 13:38:04
【问题描述】:

我有以下课程

class ContractStore {

    clauses = [];

    addClause() {
        this.clauses.push({
            id: uuidv1()
        })
    }

}

export let contractStore = new ContractStore();

然后导入为

import { contractStore } from '../store/ContractStore'
...
contractStore.addClause()

我在addClause() 方法中得到this 作为undefined。我在这里做错了什么?

【问题讨论】:

    标签: ecmascript-6 import this undefined


    【解决方案1】:

    您没有在此处设置上下文。你可以通过两种方式做到这一点。

    箭头函数方式

    class ContractStore {
    
        clauses = [];
    
        addClause = () => {
            this.clauses.push({
                id: uuidv1()
            })
        }
    
    }
    

    或 绑定方式

    class ContractStore {
        constructor() {
          this.addClause = this.addClause.bind(this)
        }
        clauses = [];
    
        addClause() {
            this.clauses.push({
                id: uuidv1()
            })
        }
    
    }
    

    谢谢。欢迎反馈

    【讨论】:

      猜你喜欢
      • 2021-08-30
      • 2017-02-15
      • 1970-01-01
      • 2013-06-19
      • 1970-01-01
      • 2019-12-11
      • 2015-11-29
      • 2018-05-19
      • 2020-11-06
      相关资源
      最近更新 更多