views:

127

answers:

1

Why are 'me' and 'this' undefined when setTimeout calls it's anonymous callback?

    var gMyObj = new MyObj();
    gMyObj.myFunc();

    function MyObj() {
        this.myFunc = function () {
            var me = this;
            alert(me.constructor);  // defined
            setTimeout(function(me) {  
                      alert(me.constructor); // undefined
                  }, 100);
        };
    }

Resolution: The selected answer is correct, thank you. My question was a simplification of the real problem I was having, which turned out to be the way jQuery modifies 'this' inside the click() method so that it points to the relevant DOM element. I had created a new var, 'me', to hold onto 'this', and was trying to pass it in to the click method. All I needed to do was just use 'me' inside the click event, and let the closure keep a reference to it. Passing 'me' into click() failed, for the same reason that it failed in this example, namely, click() was not expecting it.

+10  A: 

Because of this:

function(me) {

Make it:

function() {

And you're good to go.

As to the 'why?' part, you are defining an anonymous function that takes an argument called 'me.' When setTimeout calls that function, it passes no arguments, meaning 'me' will be assigned a value of null. Removing 'me' from the argument list allows the previously defined 'me' to be visible within the function.

Sean Bright
+1. but me has no value at all, undefined. null is a value.
AnthonyWJones