无法在JavaScript类中使用此值吗?

问题描述 投票:-1回答:1

我无法使用javascript类中的this关键字获取数据。谁能帮忙,为什么会这样呢?请检查以下示例

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的值?

javascript typescript
1个回答
0
投票
 welcomeMessage = () => {
        return axios.get("http://localhost:8080/welcome", this.__CONFIG);
    }

这将允许您使用this的词法绑定,因为箭头函数没有this值,因此将在周围的上下文中查看this的值

© www.soinside.com 2019 - 2024. All rights reserved.