3

ブラウザーで、Reflux.js アクションで ES6 promise と ES6 fetch を使用しようとしていますが、匿名矢印関数内で「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