我正在尝试传递this
以访问父属性。我很难过。我错过了一些完全明显的东西吗代码编译正确,但它没有按预期返回父代。我之前使用过这种模式但是在vanilla Javascript中。它可能与CoffeeScript声明为var
的函数有关吗?
Model = (parent) ->
@view = parent.view
console.log @view # undefined?
return
View = (parent) ->
@model = parent.model
console.log @model # undefined?
return
ViewModel = ->
@view = new View @
@model = new Model @
return
vm = new ViewModel()
答案 0 :(得分:2)
您正在传递父项的引用,但在分配@view = parent.view
时将对象内部缓存为未定义。如果在那一刻父视图未定义,则将来未定义。我想你想要的是这个:
class Model
constructor: (@parent) ->
view: -> @parent.view
class View
constructor: (@parent) ->
model: -> @parent.model
class ViewModel
constructor: ->
console.log 'this', @
@view = new View @
@model = new Model @
#console.log 'model', @model.view()
#console.log 'view', @view.model()
vm = new ViewModel()
console.log vm.model.view()
console.log vm.view.model()