JavaScript“这个”引用错误的对象
好吧,this
并没有真正引用错误 对象,但我不知道如何引用正确的对象。
function someObj() {
this.someMethod1 = function() {
var elementBtn = document.getElementById('myBtn');
elementBtn.onclick = function() {
this.someMethod2(); //I want this.someMethod2() to be called
//...but it tries to call elementBtn.someMethod2() i believe.
};
};
this.someMethod2 = function() {
alert('OK');
};
}
因此,当单击我的 myBtn
时,我希望运行 someObj.someMethod2()
。我希望它是 someObj
,而不是任何其他 someObj
。但怎么办?
Well, this
doesn't really refer to the wrong object, but I do not know how to refer to the correct one.
function someObj() {
this.someMethod1 = function() {
var elementBtn = document.getElementById('myBtn');
elementBtn.onclick = function() {
this.someMethod2(); //I want this.someMethod2() to be called
//...but it tries to call elementBtn.someMethod2() i believe.
};
};
this.someMethod2 = function() {
alert('OK');
};
}
So when my myBtn
is clicked I want someObj.someMethod2()
to run. And I want it to be that someObj
, not any other someObj
. But how?!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可能需要进行如下调整:
“that”捕获您所追求的范围。
You might need to make a tweak like this:
"that" captures the scope you are after.
函数关键字更改范围。一种解决方案是维护对您要使用的“this”的引用。
请尝试以下操作:
The function keyword changes scope. One solution is to maintain the reference to the "this" that you want to use.
Try the following:
您可以使用咖啡脚本,它有一个粗箭头(用于 onclick 函数)来处理这种事情,并编译为格式良好的 JavaScript。通过使用粗箭头,咖啡脚本可确保回调函数中使用与定义的函数相同的范围。
<一href="http://coffeescript.org/#try%3asomeObj%20%3D%20%28%29%20-%3E%0A%20%20%20%40someMethod1%20%3D% 20%28%29%20-%3E%0A%20%20%20%20%20%20elementBtn%20%3D%20document.getElementById%20%27myBtn%27%0A%20%2 0%20%20%20%20elementBtn.onclick%20%3D%20%28%29%20%3D%3E%20%0A%20%20%20%20%20%20%20%20%20% 40人冰毒od2%28%29%0A%20%20%20this.someMethod2%20%3D%20%28%29%20-%3E%0A%20%20%20%20%20%20alert%20%27OK%27 %0A” rel="nofollow">在这里玩代码
Coffee Script
JavaScript
You could use coffee script, which has a fat arrow (used for onclick function) to deal with this kind of thing, and compiles to well formed javascript. By using fat arrow, coffee script ensures the same scope as the function is defined in will be used in the callback function.
play with code here
Coffee Script
JavaScript