简体   繁体   中英

Changing the behavior of this inside object

I have got two objects ie

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.

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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM