Oop 访问coffeescript中包含的类的父类
如何从Oop 访问coffeescript中包含的类的父类,oop,coffeescript,Oop,Coffeescript,如何从item.child.activate访问item.ready?这必须有一个语法 不,没有特殊的语法。如果您需要ChildItem和ParentItem之间的关系,那么您必须自己连接它;例如: class ChildItem constructor : -> @activate() activate : -> if parent.ready #this line will fail console
item.child.activate
访问item.ready
?这必须有一个语法 不,没有特殊的语法。如果您需要ChildItem
和ParentItem
之间的关系,那么您必须自己连接它;例如:
class ChildItem
constructor : ->
@activate()
activate : ->
if parent.ready #this line will fail
console.log 'activate!'
class ParentItem
constructor : ->
@ready = true;
@child = new ChildItem()
item = new ParentItem()
不幸的是,没有语法可以神奇地访问。。。甚至像
arguments.caller这样的东西在这里也帮不上忙。但是,有几种方法可以做到这一点,但不确定您更喜欢哪一种:
1) 传入ready参数(或者可以传入整个父级)
2) 或者您可以使用extends
,这将允许ChildItem访问ParentItem的所有属性和功能:
class ChildItem
constructor: (ready) ->
@activate ready
activate: (ready) ->
if ready
console.log 'activate!'
class ParentItem
constructor : ->
@ready = true
@child = new ChildItem(@ready)
item = new ParentItem()
是的,它应该继续工作,因为孩子在@parent
.Sweeet中直接引用了ParentItem
。我要拍一张照片来确认一下。你真是太棒了!这正是我要找的!也是+1
class ChildItem
constructor: (ready) ->
@activate ready
activate: (ready) ->
if ready
console.log 'activate!'
class ParentItem
constructor : ->
@ready = true
@child = new ChildItem(@ready)
item = new ParentItem()
class ParentItem
constructor : (children) ->
@ready = true
@childItems = (new ChildItem() for child in [0...children])
class ChildItem extends ParentItem
constructor: ->
super()
@activate()
activate: ->
if @ready
console.log 'activate!'
item = new ParentItem(1)