【问题标题】:Es6 Fetch/Promise ContextEs6 获取/承诺上下文
【发布时间】: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


【解决方案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”绑定到的内容)有关,而不是内部函数本身。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-05-03
    • 1970-01-01
    • 2016-01-27
    • 2016-11-20
    • 2018-11-28
    • 2016-06-13
    • 1970-01-01
    相关资源
    最近更新 更多