I am using closure for privacy.
I dont understand why and how to change local variable from outside of closure.
I wrote a script for explain problem to you.
var MyAjax=(function(){
//Create a local variable for privacy
var _opts={
cache:true
}
,getDefaultOptions=function(){
return _opts
};
//return only getDefaultOptions function
return {
getDefaultOptions:getDefaultOptions
}
})()
//I am merging new ajax options with default options.
var defaults=MyAjax.getDefaultOptions();
var reqOptions= $.extend(defaults,{cache:false});
// I am getting expected result
console.log("extended var",reqOptions) //{cache:false}
// I am getting non expected result
// I should get {cache:true} but I am getting { cache:false }
console.log("defaults",MyAjax.getDefaultOptions()) //{cache:false}
Why this happening and how ?
The
$.extend()function modifies the first argument. If you don’t want that, do this:To elaborate: you pass a reference to the object as the first argument. Even though it’s a private variable of that closure, the getter function has returned a reference to it, so it’s “visible” that way. The jQuery function is written in such a way that it always directly updates the object passed as the first argument. Therefore, to make sure you don’t change that object, just pass in a freshly-created object as the first argument.