将`this`传递给访问其属性的函数给出了undefined?

时间:2014-11-04 16:14:30

标签: javascript coffeescript

我正在尝试传递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()

1 个答案:

答案 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()

工作小提琴:http://jsfiddle.net/8hnfkarx/