// This clobbers (over-writes) its parameter, so the change
// is not reflected in the calling code.
function Clobber(param) 
{
    // clobber the parameter; this will not be seen in 
    // the calling code
    param = new Object();
    param.message = "This will not work";
}

// This modifies a property of the parameter, which
// can be seen in the calling code.
function Update(param)
{
    // Modify the property of the object; this will be seen
    // in the calling code.
    param.message = "I was changed";
}

// Create an object, and give it a property.
var obj = new Object();
obj.message = "This is the original";

// Call Clobber, and print obj.message. Note that it hasn't changed.
Clobber(obj);
window.alert(obj.message); // Still displays "This is the original".

// Call Update, and print obj.message. Note that is has changed.
Update(obj);
window.alert(obj.message); // Displays "I was changed".

When you pass a parameter to a function by value, you are making a separate copy of that parameter, a copy that exists only inside the function. Even though objects and arrays are passed by reference, if you directly overwrite them with a new value in the function, the new value is not reflected outside the function. Only changes to properties of objects, or elements of arrays, are visible outside the function.

posted on 2013-06-17 18:30  @version  阅读(229)  评论(0)    收藏  举报