[英]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. 如您所见, Parent.beHappy()
调用child的study
方法。 Now the problem I am having is, in the study
method I cannot call this.play()
. 现在我遇到的问题是,在study
方法中我不能调用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
. 其原因,为什么会这样是因为study()
被调用的Parent
等this
在这里指的是Parent
,而不是Child
。 Is there any way that I can make this
in the study
method always refer to Child
and not the Parent
? 有没有什么办法,我可以让this
在study
方法始终是指Child
,而不是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
. 我知道我可以在study
方法中使用Child.play()
使其工作,但我希望在我的代码中保持一致,并且更喜欢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. 另外,我可以执行$.proxy(Parent.beHappy, Child)()
,但我不想更改此Parent.beHappy()
函数调用,因为它将由最终用户使用。 I have tried everything and now I am out of ideas. 我已经尝试了所有的东西,但现在我已经没有想法了。 Any suggestions will be highly appreciated. 任何建议将受到高度赞赏。
Set context using .bind()
js method: 使用.bind()
js方法设置上下文:
Parent.beHappy = this.study.bind(this);
Or to support even older browsers, use jQuery $.proxy(): 或者为了支持更旧的浏览器,使用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.