【问题标题】:Why can't call instance method inside method为什么不能在方法内部调用实例方法
【发布时间】:2017-03-09 08:00:12
【问题描述】:
class MyClass
  defaultOptions:
    url: '/photos.json'

  constructor: (@element, @options) ->
    @photos = []
    @init()

  addPhotos: (photo) ->
    @photos.push photo

  request: ->
    $.getJSON(this.defaultOptions.url).done((data) ->        
      @addPhotos data
      return
    ).fail (jqxhr, textStatus, error) ->
      err = textStatus + ', ' + error
      console.log 'Request Failed: ' + err
      return

  init: ->
    @request()

当我从控制台运行此命令时

var myClass = new MyClass("#myElement")

我收到此错误

TypeError: this.addPhotos is not a function. (In 'this.addPhotos(data)', 'this.addPhotos' is undefined)

知道为什么我无法在请求方法中调用 addPhotos 方法,我该如何调用它?

【问题讨论】:

标签: coffeescript


【解决方案1】:

您需要使用fat arrow 将外部上下文绑定到您的$.getJSON 回调。

request: ->
    $.getJSON(this.defaultOptions.url).done (data) => 
        @addPhotos data

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-10-06
    • 1970-01-01
    • 1970-01-01
    • 2013-09-26
    • 1970-01-01
    • 1970-01-01
    • 2016-06-11
    相关资源
    最近更新 更多