示例代码:
var person = {
name: 'Sam',
age: 45
};
// This function is able to modify the name property
function nameChanger (obj, name) {
obj.name = name;
}
nameChanger(person, 'Joe'); // modifies original object
但是试图在类似的功能中重新定义异议并不起作用:
var person2 = {
name: 'Ashley',
age: 26
};
function personRedefiner (obj, name, age) {
obj = {
name: name,
age: age
};
}
personRedefiner (person2, 'Joe', 21); // original object not changed
第二个示例不会修改原始对象。我必须更改函数以返回对象,然后设置person2 = personRedefiner(person2,' joe',21);
为什么第一个例子有效但第二个例子没有?