【发布时间】:2016-02-25 20:17:14
【问题描述】:
在浏览器中,我尝试将 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));
});
【问题讨论】:
-
第一种情况,不能绑定箭头函数。剩下的,首先定义的“这个”是什么?最后一个例子应该可以工作,试试 .then(function() { console.log(this)}.bind({jellybeans:true})) 它应该记录 jellybeans 对象。
-
节点还是浏览器?请提供minimal reproducible example
-
这些调用是在全局上下文中还是在对象实例中进行的?
-
this应该是什么?如果您在全局上下文中执行此操作,this应为undefined。 -
"所以我想我弄错了箭头函数的工作原理?" - 不,这确实是它们应该如何工作的。实现中要么存在一些错误(转译器?ES6 环境?),要么存在影响这一点的其他代码。
标签: javascript ecmascript-6 arrow-functions