Consider the following Javascript class:
function ClassA() {
this.someVariable = someValue;
this.myHandler = function(){
// I WANT TO CALL InnerFunction
this.innerFunction();
};
this.innerFunction = function(){
// do something that accesses/manipulates someVariable
};
this.hookUp = function(id){
document.getElementById(id).onclick = this.myHandler;
};
};
...
...
var button = document.createElement('button');
button.setAttribute('id','mybuttonid');
// append button to the document
...
...
var x = new ClassA();
x.hookUp('mybuttonid');
When I click on the button, the handler executes, however, 'this' now refers to the button element instead of the ClassA object, so it cannot resolve innerFunction().
What i need to have is a way to indicate to the handler that the context of this is the instance of ClassA (similar to $.ajax({context: this....}) where you can use 'this' in the .done() or .error() handlers), or a way to pass a reference to the instance to the handler without making the handler execute at instantiation time. For example if I try to pass 'this' as a praremter to myHandler (myHandler=function(ref){}, and then change : document.getElementById(id).onclick = this.myHandler(this);) But as you add parameters to myHandler, the function is executed at class instantiation time instead of at click time.
Any help will be greatly appreciated.
this.someVariabletry just usingvar someVariable.someVariablewill only be available within the scope of the function, so shouldn't be any need forthis. Also there's no such thing as classes in JavaScript, so your idea of usingthismight be misguided.