Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!!

I am using babel to transpile the code:

myOutsideFunction: function myOutsideFunction() {
    var _this = this;
    myObject.getMyList(function (myList) {
        _this.list = myList;
    });
},
like image 913
Besat Avatar asked Aug 16 '16 15:08

Besat


People also ask

Why this is undefined in arrow function?

It means that the this. value in the event handler always returns undefined . As mentioned earlier, the arrow function doesn't have its own this value. It uses the this value of the enclosing lexical scope.

Can we use this inside arrow function?

In short, with arrow functions there are no binding of this . In regular functions the this keyword represented the object that called the function, which could be the window, the document, a button or whatever. With arrow functions the this keyword always represents the object that defined the arrow function.

Why this keyword is undefined in JS?

The this keyword of the clickMe arrow function refers to the global object, in this case the window object. So, this. position and this. color will be undefined because our window object does not know anything about the position or the color properties.

Which one is correct code for arrow function?

// using arrow functions let x = (x, y) => x * y; using an arrow function.


1 Answers

If this is undefined within an arrow function, it's undefined outside of the arrow as well. Arrow function simply capture the this of the surrounding scope.

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.

When debugging, bear in mind that transpilers can rename variables (and have to rename this for it to capture correctly). Using the original name in the console without sourcemaps that include renaming will show you undefined even if the original value isn't. Make sure you use the transpiled name in watches or console commands.

like image 187
ssube Avatar answered Oct 19 '22 15:10

ssube