将“this”传递给访问其属性的函数会给出未定义的结果
Passing `this` to function that accesses property on it gives undefined?
我正在尝试传入this
以访问父属性。我被难住了。我是不是错过了一些显而易见的东西?代码编译正确,但没有按预期返回父级。我以前使用过这种模式,但在普通的Javascript中使用过。这可能与CoffeeScript声明为var
s的函数有关吗?
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/
相关文章:
- JScript 错误: 无法分配给函数结果
- 显示基于javascript函数结果的HTML代码
- 访问来自另一个函数的函数结果
- 将函数结果传递给Javascript中的另一个函数变量
- NaN作为函数结果而不是必需的整数出现问题
- 更改javascript更改函数结果的颜色
- 从函数结果中检测三角函数
- 根据函数结果使用 JavaScript 更改图像
- 如何返回函数结果并将它们设置为标记的内部 HTML
- JavaScript 如何将函数结果与数组中的值一起传递到同一个函数中
- 用
标记包装 JQuery 函数结果
- 节点函数结果未定义
- 使用Cheerio和Response for Node web scraper,将响应函数结果传递给视图
- 在所有项目javascript中显示函数结果
- 平板电脑友好的悬停工具提示,显示基于javascript函数结果的动态文本
- 在机器时间更改后立即更新Date()函数结果
- 屈服函数结果
- 如何在JavaScript中处理异步函数结果
- 声明和定义全局变量作为函数结果有时有效
- Jquery&函数结果,作为属性名称