Kamran Ahmed
Kamran Ahmed

Reputation: 12440

Changing the behavior of this inside object

I have got two objects i.e.

var Parent = { };

var Child = {
    born : function () {
        Parent.beHappy = this.study;
    },

    study : function () {
        console.log("Studying!");
        console.log("Now I'm going to play");
        this.play();
    },

    play : function () {
        console.log("Playing!");
    }
}

Now, what I am doing is

Child.born();
Parent.beHappy();

As you can see Parent.beHappy() calls the study method of child. Now the problem I am having is, in the study method I cannot call this.play(). And the reason, why is it so is because study() is being called on Parent and so this here refers to Parent instead of Child. Is there any way that I can make this in the study method always refer to Child and not the Parent? I know that I can do Child.play() in the study method to make it work, but I would like to be consistent throughout my code and would prefer this. Also, I could do $.proxy(Parent.beHappy, Child)(), but I don't want to change this Parent.beHappy() function call, because it will be used by the end user. I have tried everything and now I am out of ideas. Any suggestions will be highly appreciated.

Upvotes: 1

Views: 47

Answers (1)

A. Wolff
A. Wolff

Reputation: 74420

Set context using .bind() js method:

Parent.beHappy = this.study.bind(this);

Or to support even older browsers, use jQuery $.proxy():

Parent.beHappy = $.proxy(this.study, this);

var Parent = { };

var Child = {
    born : function () {
        Parent.beHappy = $.proxy(this.study, this);
    },

    study : function () {
        snippet.log("Studying!");
        console.log("Studying!");
        console.log("Now I'm going to play");
        snippet.log("Now I'm going to play");
        this.play();
    },

    play : function () {
        console.log("Playing!");
        snippet.log("Playing!");
    }
}

Child.born();
Parent.beHappy();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

Upvotes: 3

Related Questions