javascript中的按值操作和按引用操作
犀牛书第5版第3章最后一节,谈的是by value versus by reference。这一节总结得很好,对java、ruby等其他语言道理也是一样的,有空可以重读。
In javascript, as in all programming languages, you can manipulate a data value in three important ways. First, you can copy it. For example, you might assign it to a new variable. Second, you can pass it as an argument to a function or method. Third, you can compare it with another value to see whether the two values are equal. To understand any programming language, you must understand how these three operations are performed in that language.
但这里还是重点总结一下javascript中的情况。只总结结论,具体样例忘记了可以看书。
规则1:number和boolean是按值使用,Object(包括Array、Function)是按引用使用。
规则2:但是引用本身是按值传递(references themselves are passed by value)。
关于规则2,还是上个例子吧,不然有点太抽象了。
function test() {var person = {name:"michael"};alert(person.name);notChangeObject(person);alert(person.name);}function changeObject(obj){obj.name = "john";// obj是引用,因此会实际修改name的值} function notChangeObject(obj){var temp = {name:"john"};obj = temp;// obj本身是按值传递,因此person依然指向原来的对象}