I'm having trouble using "this" in my objects when the method is triggered
by an event.

Here's my basic test class. The lines that do not work as expected are in
red.

var MyClass = function(selector)
{
this.hello = 'Hello World!';
 var onClick = function()
{
alert('onclick: this = ' + this); // <-- object HTMLInputElement
alert(this.hello); // <-- does not work: undefined
otherFunc();
}
 var otherFunc = function()
{
alert('otherfunc: this = ' + this); // <-- object Window ??
alert(this.hello); // <-- does nto work: undefined
}
 $(selector).click(onClick);
 alert('loaded: this = ' + this); // <-- object Object
alert(this.hello); // <-- alerts "Hellow World!"
};

The way this works is instantiating a new MyClass object binds the click
event to the selector. This works fine, but "this" loses its scope, even
when calling other functions.

To see this in action, check out this page (watch out for the alerts ;)).

Any ideas on how to keep "this" within scope?

-Hector

Reply via email to