值引用面试题引发的思考

function changeAgeAndReference(person) {
    person.age = 25;
    person = {
        name: 'John',
        age: 50
    };
    
    return person;
}
var personObj1 = {
    name: 'Alex',
    age: 30
};
var personObj2 = changeAgeAndReference(personObj1);
console.log(personObj1); // -> ?
console.log(personObj2); // -> ?

第一眼你的答案是什么?是不是信心满满的两个一样的object

  person = {
        name: 'John',
        age: 50
    };

结果是

{name: "Alex", age: 25}
{name: "John", age: 50}

意不意外?

让我们从上往下啄行查看

var personObj1 = {
    name: 'Alex',
    age: 30
};
//开辟了以内堆内存空间 0x001 
var personObj1 = [0x001];

var personObj2 = changeAgeAndReference(personObj1); //此时传入的personOb1 是一个内存地址
 function changeAgeAndReference(person) {
        //arguments[0]:var person = [0x001]; person = personObj1的内存地址
        person.age = 25; //修改[0x001]的值
        person = { // arguments[0] 开辟了一个堆内存空间 [0x002]
            name: "John",
            age: 50
        };
        person.age = 100; //[0x002] 指向的堆地址的值发生改变
        return person; //return [0x002]
      }

//所以 personObj2  就是     name: 'John',   age: 50

你可能感兴趣的:(值引用面试题引发的思考)