首页 > 解决方案 > 无法在 JavaScript 类中使用 this 获取值?

问题描述

我无法使用thisjavascript 类中的关键字获取数据。任何人都可以帮助为什么会这样?请检查下面的示例

import axios from 'axios';

class Api {

    __HOST = "http://localhost:8080";
    __BASIC_AUTH = "Basic " + window.btoa('subhendu:mondal');
    __CONFIG = {
        headers : {
            authorization: this.__BASIC_AUTH
        }
    }

    welcomeMessage(){
        return axios.get("http://localhost:8080/welcome", this.__CONFIG);
    }

    Todo = {

        fetch: function(username, id){
            console.log(this.__CONFIG);
            return axios.get(`${this.__HOST}/users/${username}/todos/${id}`, this.__CONFIG);
        }
    }
}

export default new Api();

这里的方法里面Todo可以得到__CONFIG. 我怎样才能得到 , 的__CONFIG__HOST

标签: javascripttypescript

解决方案


将其转换为箭头函数,现在this指的是函数本身的this值,而不是类的this值。

这将允许您进行this词法绑定(即在代码中编写的位置),因为箭头函数没有this属性,它会沿着作用域链查找最近的this引用,然后到达类this值,即是你想要的。


推荐阅读