coffeescript承诺链接功能定义

Wei*_*ang 5 javascript coffeescript q

当承诺在coffeescript中进行链接时,为此定义的函数需要绑定到'this'.

  $q.fcall somecall
  .then ((url)->
    dosomething()
    ).bind(this)
  .catch (err)->
    console.log 'error occured', err
Run Code Online (Sandbox Code Playgroud)

但是,以上编译成以下内容,这是错误的.那怎么写呢?或者有没有办法让coffeescript代表这个?

  $q.fcall(somecall).then(((function(url) {
    dosomething()
  }).bind(this))["catch"](function(err) {
    return console.log('error occured', err);
  })));
Run Code Online (Sandbox Code Playgroud)

ale*_*lex 3

使用=>而不是自己绑定它,它会更容易阅读并且正确。

$q.fcall somecall
.then (url) =>
  dosomething()    
.catch (err)->
  console.log 'error occured', err
Run Code Online (Sandbox Code Playgroud)

但是,这实际上没有意义,因为您没有this在函数中引用。您可能实际上只想dosomething直接传递给then(),因此它ThisBinding被保留。

  • @WeideZhang:这有什么问题吗?`om()` 和 `o['m']()` 是等价的,并且 [`catch` 是一个关键字](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/语句/try...catch) 所以 CoffeeScript 使用字符串形式。 (4认同)