JavaScript 的純值為傳值,物件為傳參照
var num = 1;
var str = '一';
var num2 = num;
var str2 = str;
num2 = 2;
str = '二';
console.log(num, num2); // 1 2
console.log(str, str2); // 一 二
var person = {
name: 'Carol',
age: 18
};
var person2 = person;
console.log(person); // {name: 'Carol', age: 20}
console.log(person2); // {name: 'Carol', age: 20}
function fn(person) {
person.age = 20;
person = {
name: 'Mary',
};
return person;
}
var person = {
name: 'Carol',
age: 18
};
var person2 = fn(person);
console.log(person); // {name: 'Carol', age: 20}
console.log(person2); // {name: 'Mary'}
var person = {
name: 'Carol',
age: 18
};
var person2 = person;
person.age = 20;
person = {
name: 'Mary',
};
console.log(person); // {name: 'Mary'}
console.log(person2); // {name: 'Carol', age: 20}