I am having a problem with the use of "this". Maybe someone can help
me out here, let me know if I am doing this wrong:
Lets say I have an object MyObject, which has local variables, and some
methods. One of the local variables is an HTML input box. On
mousedown I want to execute some code like this:
function MyObject(inputF ieldID){
// get the HTML element
this.InputField = document.getEle mentById(inputF ieldID);
// local variable
this.MyID = inputFieldID;
// function trying to run
this.MyFunction = function(){
alert(this.MyID );
}
this.InputField .onkeydown = this.MyFunction ;
}
Now when you keydown inside the input textbox it errors because inside
the MyFunction function "this" doesn't refer to the object MyObject,
but rather to the Input element.
The only workaround I have found is to give the InputField a reference
to its owner so you have:
this.InputField .MyObject = this;
And then when your MyFunction becomes:
this.MyFunction = function(){
alert(this.MyOb ject.MyID);
}
That works, but it seems like a pain to have to carry those references.
Is there another way to do this?
me out here, let me know if I am doing this wrong:
Lets say I have an object MyObject, which has local variables, and some
methods. One of the local variables is an HTML input box. On
mousedown I want to execute some code like this:
function MyObject(inputF ieldID){
// get the HTML element
this.InputField = document.getEle mentById(inputF ieldID);
// local variable
this.MyID = inputFieldID;
// function trying to run
this.MyFunction = function(){
alert(this.MyID );
}
this.InputField .onkeydown = this.MyFunction ;
}
Now when you keydown inside the input textbox it errors because inside
the MyFunction function "this" doesn't refer to the object MyObject,
but rather to the Input element.
The only workaround I have found is to give the InputField a reference
to its owner so you have:
this.InputField .MyObject = this;
And then when your MyFunction becomes:
this.MyFunction = function(){
alert(this.MyOb ject.MyID);
}
That works, but it seems like a pain to have to carry those references.
Is there another way to do this?
Comment