I’m having a hard time grasping the concept of closures and variable scope in JS. Specifically, how do I access the deeply nested styleData variable in a class and then an object created from that class?
I’m sure I have a few other things wrong here, so please chime in and correct me where you see fit. Thanks!
var BuildJSON = {
convert: function() {
$.ajax({
type: "GET",
url: "style2.xml",
dataType: "xml",
success: function(xml) {
var styleData = $.xml2json(xml);
return styleData; // Do I need to return this somehow?
}
//How to get access to styleData??
});
},
styleData: this.convert();
};
var myClass = function() {
this.info = BuildJSON.styleData;
};
var myObject = new myClass;
alert(myObject.info.Style[0].name);
Closures in JavaScript are functions, so anything declared within a function scope will ONLY be visible inside that function.
In your example
styleDatais local, it belongs to thesuccessfunction, and can’t be accessed anywhere else. The easiest solution is to declare that variable at the top of theBuildJSONscope, in this case since you’re declaring that object as an object literal you can initialize it as a property of that object:The “problem” with this approach is that
styleDatais public, and maybe that’s not what you want. In case you want to use that variable inside BuildJSON but not make it publicly accessible, the module pattern comes to the rescue.