3

在浏览器中,我尝试将 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));
});

4

1 回答 1

1

当我尝试简化版本的箭头函数版本时:

function listenAndPromise() {
 console.log('outer fn',this);
  return fetch('crew.json')
  .then(() => {
    console.log('arrowfn',this);  // undefined
  })
}
listenAndPromise.bind({test:4})();

它记录外部 fn Object {test: 4} 然后是 arrowfn Object {test: 4}

这就是我所期望的。外部函数被赋予 this 上下文,箭头函数不会添加新的“this”上下文/含义。您的结果可能与您的环境(或 CrewActions.fetchCrew.listenAndPromise 将“this”绑定到的内容)有关,而不是内部函数本身。

于 2016-02-25T22:28:43.190 回答