gpt4 book ai didi

javascript - this 在箭头函数中未定义

转载 作者:数据小太阳 更新时间:2023-10-29 05:25:08 26 4
gpt4 key购买 nike

我试图在我的箭头函数中访问它:

import myObject from '../myObjectPath';
export const myClass = Fluxxor.createStore({
initialize() {
this.list = [];
this.id = null;
},
myOutsideFunction(variable1) {
// here this in NOT undefined
myObject.getMyList(this.id, (myList) => {
// here this in undefined
this.list = myList;
}
});
)};

但是在回调函数中的箭头函数中,this 是未定义的!!

我正在使用 babel 来转译代码:

myOutsideFunction: function myOutsideFunction() {
var _this = this;
myObject.getMyList(function (myList) {
_this.list = myList;
});
},

最佳答案

如果 this 在箭头函数内是 undefined,那么它在箭头外也是未定义的。箭头函数简单地捕获周围作用域的 this

在这种情况下,您将 myOutsideFunction 声明为对象文字上的方法,并且永远不会绑定(bind)它或做任何其他会用对象作为 this 调用它的事情.

调试时,请记住转译器可以重命名变量(并且必须重命名 this 才能正确捕获)。在没有包含重命名的源映射的控制台中使用原始名称将显示 undefined,即使原始值不是。确保在 watch 或控制台命令中使用转换后的名称。

关于javascript - this 在箭头函数中未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38978387/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com