簡體   English   中英

更改此內部對象的行為

[英]Changing the behavior of this inside object

我有兩個對象,即

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!");
    }
}

現在,我正在做的是

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

如您所見, Parent.beHappy()調用child的study方法。 現在我遇到的問題是,在study方法中我不能調用this.play() 其原因,為什么會這樣是因為study()被調用的Parentthis在這里指的是Parent ,而不是Child 有沒有什么辦法,我可以讓thisstudy方法始終是指Child ,而不是Parent 我知道我可以在study方法中使用Child.play()使其工作,但我希望在我的代碼中保持一致,並且更喜歡this 另外,我可以執行$.proxy(Parent.beHappy, Child)() ,但我不想更改此Parent.beHappy()函數調用,因為它將由最終用戶使用。 我已經嘗試了所有的東西,但現在我已經沒有想法了。 任何建議將受到高度贊賞。

使用.bind() js方法設置上下文:

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

或者為了支持更舊的瀏覽器,使用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> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM