Forum Moderators: open

Message Too Old, No Replies

Referencing an object's method

         

Fotiman

11:53 pm on Nov 21, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



I have a JavaScript object. In the constructor for the object, I want to assign one of the page's event handlers to a member function of the object instance. However, when that member function is called, the "this" reference seems to be for the object with the event instead of my object. Is there a way around this? For example:

<select id="foo"><option value="1">1</option><option value="2">2</option></select>
<script type="text/javascript">
function myClass( elementId )
{
this.elementId = elementId;
this.el = document.getElementById(elementId);
this.el.onchange = this.doSomething;
}
function doSomething()
{
alert(this.elementId); // "this" is not my object
}
myClass.prototype.doSomething = doSomething;

var myObj = new myClass( 'foo' );
</script>

Bernard Marx

1:56 am on Nov 22, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



this.el.onchange = this.doSomething;

This statement assigns the function doSomething to the onchange event. The fact the reference was gained via the object is irrelevant. In other words, it's the same as this:

this.el.onchange = doSomething;

So when the event happens, the function is called in the context of the select object. To have it like you want, create a closure by wrapping the call in another function:

this.el.onchange = function(){ this.doSomething() };

Fotiman

3:50 pm on Nov 22, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month




So when the event happens, the function is called in the context of the select object. To have it like you want, create a closure by wrapping the call in another function:

this.el.onchange = function(){ this.doSomething() };

This actually seems to do the same thing. If I add an alert(this) in that function wrapper, I see that it's the select object still, not my object.

I did find a solution though:

this.el.onchange = createReference(this,"doSomething");

function createReference(obj,methodName)
{
return function() {
obj[methodName]();
};
}