I was told on another thread that after the function exits, any modifications made to its operands from within the function will persist. I always thought that it made a temporary copy of all the values passed into it, and then the only things that persisted were return values and implicitly more broadly scoped variables that were modified.
I suppose thinking back to all the jquery plugins whose source code I’ve peaked at, they all use the construct:
(function($){
$.fn.foo = function(){ console.log('foo'); };
})(jQuery);
which imply that modifications to the jQuery object even by the internal-scope $ identifier persist after the function exits, or the jQuery plugins would not work. So, this works as the above snippet does:
var x = {n:0};
(function addOneTo(p) {
p.n = p.n + 1;
})(x);
console.log(x);
But this:
var x = 0;
(function addOneTo(p) {
p = p + 1;
})(x);
console.log(x);
doesn’t, leaving x unmodified with a value of 0.
Could someone just explain how argument passing works? I thought I knew how it did, but I guess I don’t. Thanks
Actually in your first example
The
xis an object and when you usedp.n = p.n + 1;it modified the original object’s property because it passed as a reference (p is the same object as x) but in your second examplexis passed by a value in to the function andp = p + 1;herepis a new private variable inside that function and it has only the function scope.