0

I have another javascript/jQuery's variables scope questions to ask...

Say I declared a object named Container. In which there is a variables called myimage which will read a address from some xml file.

 Container = function()
 {
   var myimage;
 }

 Container.prototype.readXML = function()
 {
   $.get("assest/xml/images.xml",function(xml)
{
    //Read in URL path from XML file, and store them into memeber variables
    myimage = $(xml).find('background').text();
    //Apply background image into body, and apply css styple into it
    $("body").css('background-image','url(' + myimage + ')');
            //This alert will work
            alert(myimage);
});
            //This alert gives not defined variable
    alert(myimage);
  }

Please look at the two alert section. It seems this variable I defined in the Container object, can only work inside that readXML function. but not out. I can't understand why this happend.

I do use some other notation, like declare with this.myimage and access it by change name of this to self before execute the $.get function var self= this;

But it get worse. Sometimes it even can't be reached anymore inside the get function.

Could you help me with this? My final goal is an array in that object and read bunch of data from XML than display them into HTML. If the variables I set in the Object can't be reached, there is no way I can do that.

Thank you!!

Arthur0902
  • 209
  • 3
  • 14
  • In your "readXML()" function, that "myimage" variable is **not** the local variable declared in the constructor - instead, it's a **global** variable. The reason your second alert doesn't work is that the variable is not defined until the ajax call is complete. – Pointy Aug 23 '12 at 17:22

2 Answers2

1
 Container = function()
 {
   var myimage;
 }

should most likely be defined as below. More importantly, $.get is asynchronous so you cannot assume it finishes each line of code in the order it's written.

 var Container = function()
 {
   this.myimage = '';
 }

Container.prototype.readXML = function(callback) {
    $.get("assest/xml/images.xml", function(xml) {
        //Read in URL path from XML file, and store them into memeber variables
        this.myimage = $(xml).find('background').text();
        //Apply background image into body, and apply css styple into it
        $("body").css('background-image', 'url(' + this.myimage + ')');
        //This alert will work
        callback(this.myimage);
    });
}​

var instance = new Container();
instance.readXML(function (copy) {
    alert(copy);
});​
Joe
  • 80,724
  • 18
  • 127
  • 145
0

All variables in Javascript that are not declared in the global scope are local to the function they are declared in.

Since functions are objects in Javascript, you can assign properties to them. So, you can do

Container.myimage = $(xml).find('background').text();
//...
alert(Container.myimage);
Peter Olson
  • 139,199
  • 49
  • 202
  • 242