Function 有没有办法避免使用';呼叫';用咖啡脚本?

Function 有没有办法避免使用';呼叫';用咖啡脚本?,function,call,this,coffeescript,Function,Call,This,Coffeescript,我正在编写一个简单的Twitter客户端来使用coffeescript。我有一个对象文本,其中包含一些通过回调相互调用的函数 somebject = foo: 'bar' authenticateAndGetTweets: -> console.log "Authorizing using oauth" oauth = ChromeExOAuth.initBackgroundPage(this.oauthdetails) oauth.authorize( t

我正在编写一个简单的Twitter客户端来使用coffeescript。我有一个对象文本,其中包含一些通过回调相互调用的函数

somebject =
  foo: 'bar'
  authenticateAndGetTweets: ->
    console.log "Authorizing using oauth"
    oauth = ChromeExOAuth.initBackgroundPage(this.oauthdetails)
    oauth.authorize( this.afterLogin.call this )
  afterLogin: ->
    this.getTweets(this.pollinterval)
这段代码工作得很好编辑:实际上,这个.afterlogin应该作为上面的回调发送,而不是像特雷弗在下面提到的那样立即运行

如果在authenticateAndGetTweets中,我删除了“调用”并仅运行:

oauth.authorize( this.afterLogin )
如果不使用“call”,则会出现以下错误:

Uncaught TypeError: Object [object DOMWindow] has no method 'getTweets
这很有意义,因为afterLogin中的“this”绑定到启动回调的对象,而不是“someobject”我的对象文本

我想知道咖啡脚本中是否有一些魔力,我可以用它来代替“呼叫”。最初我认为使用“=>”,但是如果使用“=>”,代码将给出与上面相同的错误

有没有办法避免使用call?还是说咖啡脚本并没有消除对它的需求?是什么使“=>”无法按我的预期工作


谢谢。到目前为止,我真的很喜欢coffeescript,希望确保我的工作方式是“正确的”。

您必须使用call或apply方法,因为它们设置了函数的范围(此函数的值)。由于默认范围是
窗口
对象,因此会产生错误。

您可以像这样在函数调用中放置lambda

auth.authorize(=> @afterLogin())

正如马特尔在评论中指出的那样,这一行

oauth.authorize( this.afterLogin.call this )
不会导致
oauth.authorize将
this.afterLogin
作为回调调用;相反,它相当于

oauth.authorize this.afterLogin()
假设您希望
this.afterLogin
用作
oauth.authorize
的回调,megakorre的回答给出了一个正确的CoffeeScript习惯用法。matyr指出,许多现代JS环境支持的另一种方法是编写

oauth.authorize( this.afterLogin.bind this )
没有CoffeeScript的简写,部分原因是并非所有主流浏览器都支持
Function::bind
。您还可以使用以下库中的
bind
函数:

最后,如果要将
someobject
定义为类,则可以使用
=>
在登录后定义
afterLogin
,使其始终绑定到实例,例如

class SomeClass
  foo: 'bar'
  authenticateAndGetTweets: ->
    console.log "Authorizing using oauth"
    oauth = ChromeExOAuth.initBackgroundPage(this.oauthdetails)
    oauth.authorize(this.afterLogin)
  afterLogin: =>
    this.getTweets(this.pollinterval)

someobject = new SomeClass

是的,但我不懂你的密码
this.afterLogin.call this
立即调用它(它与
@afterLogin()
相同),其中
this.afterLogin
检索函数。你确定你不是在找吗?Matyr我提到我已经在问题的标题中使用了'call',所以说'use call'并不是一个很好的答案。不过,您的第二个问题说明了一个很好的观点:我实际上是在运行一个函数,而不是指定一个作为回调运行的函数(这正是我想要做的)。我现在来看看。嗯,是的,我的意思是“为什么
.call
?你的意思是
.bind
?”很抱歉让你更加困惑。谢谢特雷弗的全面回答:我确实希望这个.afterLogin作为回调运行,将“this”设置为afterLogin所属的对象。酷,请参阅扩展答案以了解更多想法。再次感谢Trevor:使用对象文字与使用类还回答了我的第二个问题:为什么=>没有像我预期的那样工作。谢谢,用lambda包装也很有效-向上!然而,在这种情况下,我总是希望使用this作为其属性的对象来调用函数,因此@Trevor建议使用类and=>更合适。
class SomeClass
  foo: 'bar'
  authenticateAndGetTweets: ->
    console.log "Authorizing using oauth"
    oauth = ChromeExOAuth.initBackgroundPage(this.oauthdetails)
    oauth.authorize(this.afterLogin)
  afterLogin: =>
    this.getTweets(this.pollinterval)

someobject = new SomeClass