简体   繁体   English

这是箭头函数内部未定义的

[英]this is undefined inside arrow function

I am trying to access this inside my arrow function: 我试图在我的箭头函数内访问此函数:

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

But inside arrow function which in ma callback function this is undefined!! 但是里面的箭头函数在ma回调函数中是未定义的!

I am using babel to transpile the code: 我正在使用babel来翻译代码:

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

If this is undefined within an arrow function, it's undefined outside of the arrow as well. 如果thisundefined箭头函数中,它的箭头的不确定之外也是如此。 Arrow function simply capture the this of the surrounding scope. 箭头功能仅捕获周围范围的this范围。

In this case, you're declaring myOutsideFunction as a method on an object literal and never binding it or doing anything else that would call it with the object as this . 在这种情况下,您将myOutsideFunction声明为对象文字的方法,并且从不对其进行绑定或执行任何其他操作,例如使用this调用。

When debugging, bear in mind that transpilers can rename variables (and have to rename this for it to capture correctly). 在调试时记住,记住,transpilers可以重命名变量(并有重命名this它正确地捕获)。 Using the original name in the console without sourcemaps that include renaming will show you undefined even if the original value isn't. 在控制台中使用不带重命名的源映射的原始名称将显示undefined即使原始值不是。 Make sure you use the transpiled name in watches or console commands. 确保在监视或控制台命令中使用已转换的名称。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM