javascript - 无法在 JavaScript 类中使用 this 获取值?
问题描述
我无法使用this
javascript 类中的关键字获取数据。任何人都可以帮助为什么会这样?请检查下面的示例
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
?
解决方案
将其转换为箭头函数,现在this
指的是函数本身的this
值,而不是类的this
值。
这将允许您进行this
词法绑定(即在代码中编写的位置),因为箭头函数没有this
属性,它会沿着作用域链查找最近的this
引用,然后到达类this
值,即是你想要的。
推荐阅读
- caching - 直接映射缓存示例
- javascript - CC/Javascript 更改停止颜色
- python - Django trans 模板标签只显示占位符常量字符串
- python - python3中的嵌套for循环:产生两个for循环的输出
- laravel - Blade.php 文件中的脚本标签重复
- 3d - Google Model Viewer – 有没有办法添加自定义光标?
- babeljs - 尝试运行 babel:“找不到模块 @babel/core”
- php - 如何在 PHP 中更新多个文件
- google-cloud-endpoints - Google Cloud Run 的通配符路径代理
- bash - 循环通过 docker 输出,直到我在 bash 中找到一个字符串