我对 Coffeescript 树实现中的意外行为有疑问,想知道是否有人可以提供帮助。我认为问题与错误的“this”上下文有关,但我不确定在哪里放置粗箭头来解决它。也许比我更了解咖啡脚本的人可以解释这种行为?
class Node
uuid: undefined
constructor: (@uuid) ->
class MultiNode extends Node
branches: {}
constructor: (args...) ->
super(args...)
print: (str = '') ->
console.log "#{str}Multiway<#{@uuid}>"
for value,node of @branches
if node?
node.print "#{str} "
class LeafNode extends Node
value: undefined
constructor: (@value, args...) ->
super(args...)
print: (str = '') ->
console.log "#{str}Leaf<#{@uuid}>: #{@value}"
tree = new MultiNode(1)
subtree1 = new MultiNode(2)
subtree1.branches["aa"] = new LeafNode("three",3)
subtree1.branches["ab"] = new LeafNode("four",4)
tree.branches["a"] = subtree1
subtree2 = new MultiNode(5)
subtree2.branches["ba"] = new LeafNode("six",6)
subtree2.branches["bb"] = new LeafNode("seven",7)
tree.branches["b"] = subtree2
tree.print()
我认为这会无限重复,因为“打印”的上下文没有像我打算的那样设置为子节点对象的上下文。我会很感激任何指导。
D.