在浏览器中,我尝试将 ES6 承诺和 ES6 提取与 Reflux.js 操作一起使用,但我无法在匿名箭头函数中绑定“this”的上下文。我究竟做错了什么?
* 更新 * 我正在使用 Reflux.js ListenAndPromise,我可能应该在我的原始问题中添加这个
* 更新 *
当我删除外部箭头函数时,上下文工作正常这有效:
CrewActions.fetchCrew.listenAndPromise(function() {
fetch('crew.json')
.then(function() {
console.log(this); // This is bound as expected
}.bind(this))
});
但这不起作用
CrewActions.fetchCrew.listenAndPromise(function() {
fetch('crew.json')
.then(() => {
console.log(this); // undefined
})
});
所以我想我对箭头函数的工作方式有误吗?我以为他们绑定了这个上下文?
以下示例均无效。
例子。
CrewActions.fetchCrew.listenAndPromise(() => {
console.log(this)
// functor() {
// var triggerType = functor.sync ? "trigger" : "triggerAsync";
// return functor[triggerType].apply(functor, arguments);
// }
fetch('crew.json')
.then(_.bind(() => {
console.log(this) // undefined
}, this))
fetch('crew.json')
.then(() => console.log(this)); // undefined
fetch('crew.json')
.then(function() {
console.log(this) // undefined
});
fetch('crew.json')
.then(function() {
console.log(this) // undefined
}.bind(this));
});