Forum Moderators: open
<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>
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() };
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]();
};
}