我无法使用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
的值?
welcomeMessage = () => {
return axios.get("http://localhost:8080/welcome", this.__CONFIG);
}
这将允许您使用this
的词法绑定,因为箭头函数没有this
值,因此将在周围的上下文中查看this
的值