On 07/04/2005 06:06, cainlevy wrote:
Something that's been bugging me for a while: I can't figure out how to
register an object method as an event handler, and still use the 'this'
keyword inside the handler to refer to the object. For example:
The value of the this operator varies based on the circumstances in
which it's used. Within the body of a function, the this operator
takes on two possible value types: a reference to the global object,
or a reference to an object.
If the function is called directly, for example
var myFunction = myObj.myMethod;
myFunction();
the this operator will "point" to the global object. If the function
object is called through a property accessor, for example
myObj.myMethod();
the this operator will "point" to the referenced object; myObj in this
case.
this.toString = function(){return 'myObj'};
Unless the returned string changes, this too should be placed on the
prototype object.
document.getElementById('test_tag_id').onclick = this.test;
Here, you assign a function reference to a property of a different
object. When that function is invoked, it is done so as a property of
this new object. That's why you have a reference to the table, and not
the original object.
You might work around this in two ways:
1) Assign a reference to the original object to the element. You can
then use this reference in your listener code.
myObj.myMethod = function() {
/* Use
*
* this.obj
*
* to refer to myObj.
*/
};
element.obj = myObj;
element.onclick = myObj.myMethod;
2) Use a closure. There is more than one solution using this
approach. One might be:
function MyObj() {
var self = this;
this.myMethod = function() {
/* Use self to refer to an instance of MyObj,
* irrespective of how this function is called.
*/
};
}
Hope that helps,
Mike
--
Michael Winter
Replace ".invalid" with ".uk" to reply by e-mail.