Javascript Callback/Object conflict

Giganews Newsgroups
Subject: Javascript Callback/Object conflict
Posted by:  Hoss (todd.fre…@gmail.com)
Date: 2 Sep 2006

Hello- I have the following Javascript code

function Obj()
{
        obj.squares = new Array();
}
Obj.prototype.Load= function(xdoc)
{
        var goat = "head";
    xdoc.ProcessNodes("squares/square", function(node)
      {
              alert(goat);    // <-- this works fine
              this.squares.push(
                // do processing on node, create a square
              );
      });
}

Now the xdoc is another object I have, with a method called
ProcessNodes. The only important thing to know about ProcessNodes is
that it does some things, and calls its second argument (which is a
function) successively.

The problem I am running into here is once I get into the callback
function, "this.squares" is returning null ... even though it has been
initialized to an Array. For whatever reason, its like the object loses
scope when I get into the callback function. For all other intents and
purposes however, the callback function has the same scope as the
calling block (i.e. the goat variable is still accessible).

Any ideas? Seems like a bug to me.

Replies