这在箭头函数中是未定义的

时间:2016-08-16 15:04:33

标签: javascript this undefined arrow-functions

我想在我的箭头功能中访问它:

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;
        } 
    });
)};

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

我正在使用babel来传输代码:

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

1 个答案:

答案 0 :(得分:4)

如果箭头函数中thisundefined,则箭头外部也未定义。箭头功能只是捕获周围范围的this

在这种情况下,您将myOutsideFunction声明为对象文字上的方法,并且永远不会将其绑定或执行任何其他可以将对象称为this的方法。

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

相关问题