将“this”传递给访问其属性的函数会给出未定义的结果

Passing `this` to function that accesses property on it gives undefined?

本文关键字:函数 结果 未定义 属性 访问 this      更新时间:2023-09-26

我正在尝试传入this以访问父属性。我被难住了。我是不是错过了一些显而易见的东西?代码编译正确,但没有按预期返回父级。我以前使用过这种模式,但在普通的Javascript中使用过。这可能与CoffeeScript声明为vars的函数有关吗?

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

当您分配@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/