1

When i run this code:

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

why the alert is sayng "tulio" instead of "james"? Aparently the callback dont know about this(@) how can i get "james" ?

1
  • @dog_name = this.dog_name or the_dog.dog_name. but this isn't bound to the context of Dog. So its not the same variable. Commented Oct 31, 2014 at 1:11

1 Answer 1

2

Because the_method is the callback it needs to be bound to the context of this:

http://jsfiddle.net/uaxrgrom/

the_method: ()=>
    @dog_name = "james"

alternatively it needs to be bound on the call

the_bird.bird_sing => @the_method(args...)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.