I am basically trying to alter an object outside of my ajax callback but the results are not as I had initially expected. I have simplified my project to a very easy to understand example, but there is clearly something I am not grasping.
Here is the function that contains the ajax request and callback:
var testFun = function(obj){
$.get("test.xml",function(xml){
//parse xml here...
obj.name = "B";
});
};
This is the code that is outside of the function:
var o1 = new Object();
o1.name = "A";
console.log(o1);
testFun(o1);
console.log(o1);
I would have expected to have an output as such:
Object {name: "A"}
Object {name: "B"}
But Instead am given the output:
Object {name: "A"}
Object {name: "A"}
From what I understand the object is passed as a copy of a reference of the object, so any attribute changes should stick. What am I missing here and how can I actually change that object in the callback?
EDIT: This is how I solved the problem thanks to this post This is the function being called making the ajax request
function testFun(obj){
return $.get("test.xml",function(xml){
obj.name = "B";
});
}
This is the code calling the function
var o1 = new Object();
o1.name = "A";
console.log(o1);
testFun(o1).done(function(result){
console.log(o1);
}).fail(function (){
console.log("error");
});
And this is the expected and actual output:
Object {name: "A"}
Object {name: "B"}