当将原语作为参数传递给 JavaScript 函数时,是传递给函数的值的副本(即正在创建的新变量),还是只是指向内存中变量位置的指针,就像对象发生的情况一样?然而,由于对象是可变的,因此很容易证明,因为原语是不可变的,所以它们总是会被重新分配,因此很难判断幕后发生了什么。
在以下代码(http://jsbin.com/egufog/2/edit)中演示了我的意思:
var pvalue = 'foo'; //primitive
var ovalue = { foo : 'foo' }; //object
changeMe( pvalue, ovalue ); //changes values
console.log( pvalue, ovalue ); //pvalue unchanged, ovalue was changed
reassignMe( ovalue ); //reassigns the object, breaking the reference
console.log( ovalue ); //ovalue remains unchanged
function changeMe( primitive, obj ){
primitive = 'bar'; //did this reassign the pointer or just create another variable?
obj.foo = 'bar'; //updates the object in memory
}
function reassignMe( obj ) {
obj = { baz : 'baz' }; //reassignment breaks the pointer reference
}