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;
});
},
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.
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.
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.
// using arrow functions let x = (x, y) => x * y; using an arrow function.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With