JavaScript“this”引用错误的对象 [英] JavaScript "this" references wrong object
本文介绍了JavaScript“this”引用错误的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
好吧, 这个 并没有真正引用错误的对象,但我不知道如何引用正确的对象。
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');
};
}
所以当我的 myBtn 单击strong>我想要 someObj.someMethod2() 来运行。我希望它是 someObj ,而不是任何其他 someObj 。但是如何?!
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?!
推荐答案
您可能需要进行如下调整:
You might need to make a tweak like this:
function someObj() {
var that = this;
this.someMethod1 = function() {
var elementBtn = document.getElementById('myBtn');
elementBtn.onclick = function() {
that.someMethod2();
};
};
this.someMethod2 = function() {
alert('OK');
};
}
that捕获你所追求的范围。
"that" captures the scope you are after.
这篇关于JavaScript“this”引用错误的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文