为什么不能在方法内部调用实例方法
Why can't call instance method inside method
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 方法吗?我该如何调用它?
您需要使用 fat arrow 将外部上下文绑定到您的 $.getJSON
回调。
request: ->
$.getJSON(this.defaultOptions.url).done (data) =>
@addPhotos data
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 方法吗?我该如何调用它?
您需要使用 fat arrow 将外部上下文绑定到您的 $.getJSON
回调。
request: ->
$.getJSON(this.defaultOptions.url).done (data) =>
@addPhotos data