admin管理员组文章数量:1327975
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;
});
},
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;
});
},
Share
Improve this question
edited Aug 16, 2016 at 15:35
Besat
asked Aug 16, 2016 at 15:04
BesatBesat
1,43813 silver badges29 bronze badges
7
-
Bind
this
, or store it in a temp variable outside the arrow function scope. – Jite Commented Aug 16, 2016 at 15:06 -
The value of
this
depends on howmyOutsideFunction
is called. How is it called? – Felix Kling Commented Aug 16, 2016 at 15:07 - 1 @Jite the whole idea of using arrow function is to not having to bind this! – Besat Commented Aug 16, 2016 at 15:25
- 1 @ Felix Kling myOutsideFunction is called from another function inside the class. But it shouldn't matter since myOutsideFunction HAS this. – Besat Commented Aug 16, 2016 at 15:26
- 1 @Jite Np :)) Although it does not work for me :D – Besat Commented Aug 16, 2016 at 15:27
1 Answer
Reset to default 5If 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 mands.
本文标签: javascriptthis is undefined inside arrow functionStack Overflow
版权声明:本文标题:javascript - this is undefined inside arrow function - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742251915a2440921.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论