【问题标题】:how to refer the parent object in an event handler using Coffeescript fat arrow如何使用 Coffeescript 胖箭头在事件处理程序中引用父对象
【发布时间】:2013-02-02 10:06:55
【问题描述】:

您好,我是 Js 和 Coffeescript 的新手,在下面的示例中,我觉得很难引用父对象的属性 App

App =
  init: ->
    this.foo = 'bar'
    this.bindEvent()
  bindEvent: ->  
    $('#test').click(this.show)
  show: ->
    alert this.foo

App.init()

我认为胖箭头可以解决问题,但是一旦我更改为show: =>,this 在show 方法的上下文中指的是窗口对象,而不是我想要的App 对象 .谁能告诉我怎么做对吗?

http://jsfiddle.net/kZpHX/

【问题讨论】:

标签: coffeescript arrow-functions


【解决方案1】:

当您定义 show 函数时,@(又名 this)实际上是 window 所以

show: => console.log(@)

将show 绑定到window。问题是您只是定义了一个对象,所以没有任何东西可以绑定:您没有定义一个类,所以this 是window。你可以像这样明确地引用App:

App =
  #...
  show: -> alert(App.foo)

演示:http://jsfiddle.net/ambiguous/3sRVh/

init 中的 this.foo 会做正确的事情,因为说 App.init() 会设置预期的 this。

您也可以手动连接所需的this:

bindEvent: ->
  $('#test').click => @show()

# or
bindEvent: ->
  _this = @ # JavaScript style
  $('#test').click -> _this.show()

演示:http://jsfiddle.net/ambiguous/byL45/、http://jsfiddle.net/ambiguous/MT8fG/

或者您可以为您的应用创建一个类:

class App
  constructor: ->
    @foo = 'bar'
    @bindEvent()
  bindEvent: ->  
    $('#test').click(@show)
  show: =>
    console.log(@foo)

new App

这样您的show: => 就会按照您的预期行事。

演示:http://jsfiddle.net/ambiguous/byatH/

【讨论】:

    猜你喜欢
    • 2012-09-20
    • 2014-02-28
    • 2019-05-13
    • 1970-01-01
    • 2019-03-20
    • 2011-08-25
    • 2012-05-26
    • 1970-01-01
    相关资源
    最近更新 更多