In the case you are trying to use it, the first instance of "this" is
referring to the root function object. this.hello is an item inside
that object. when you create the other 2 functions, "this" no longer
means what it did originally. If you want to pass the information of
"this", you need to replace "this" with obj and set obj to "this" in
the root function. Like this:

var MyClass = function(selector)
{
        obj = this;
        obj.hello = 'Hello World!';

        alert('loaded: this = ' + obj); // <-- object Object
        alert(obj.hello); // <-- alerts "Hellow World!"

        var onClick = function()
        {
                alert('onclick: this = ' + obj); // <-- object HTMLInputElement
                alert(obj.hello); // <-- does not work: undefined
                otherFunc();
        }

        var otherFunc = function()
        {
                alert('otherfunc: this = ' + obj); // <-- object Window ??
                alert(obj.hello); // <-- does nto work: undefined
        }

        $(selector).bind("click", onClick);
};

$(document).ready(function()
{
        var a = new MyClass('#clickme');
});

hth
Brian.

On Nov 10, 7:18 pm, "Hector Virgen" <[EMAIL PROTECTED]> wrote:
> Here's the link to the test page:http://www.virgentech.com/sandbox/this.html
>
> -Hector
>
> On Mon, Nov 10, 2008 at 5:17 PM, Hector Virgen <[EMAIL PROTECTED]> wrote:
> > 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