This question already has an answer here:
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?!
The function keyword changes scope. One solution is to maintain the reference to the "this" that you want to use.
Try the following:
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
You might need to make a tweak like this:
"that" captures the scope you are after.