繁体   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