Oop 通过类回调中的Coffeescript类实例
当我运行此代码时:Oop 通过类回调中的Coffeescript类实例,oop,coffeescript,instance,Oop,Coffeescript,Instance,当我运行此代码时: class Dog constructor: ()-> @dog_name = "tulio" the_bird = new Bird() the_bird.bird_sing(@the_method) @say_name() the_method: ()-> @dog_name = "james" say_name: ()-> ale
class Dog
constructor: ()->
@dog_name = "tulio"
the_bird = new Bird()
the_bird.bird_sing(@the_method)
@say_name()
the_method: ()->
@dog_name = "james"
say_name: ()->
alert @dog_name
class Bird
bird_sing: (callback)->
callback()
the_dog = new Dog()
为什么警报上说的是“tulio”而不是“james”?
很可能回拨者不知道这件事(@)
如何获取“james”因为
方法是回调,它需要绑定到以下上下文:
或者,它需要在通话中绑定
the_bird.bird_sing => @the_method(args...)
@dog\u name
=此.dog\u name
或狗.dog\u name
。但是这个
并没有绑定到狗的上下文
。所以它不是同一个变量。
the_bird.bird_sing => @the_method(args...)