为什么我们可以使用函数参数修改对象,但是我们不能以相同的方式重新定义对象? [重复]

时间:2022-09-06 00:26:08

This question already has an answer here:

这个问题在这里已有答案:

Example code:

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

But trying to redefine the objection in a similar function doesn't work at all:

但试图在类似的功能中重新定义反对意见根本不起作用:

var person2 = {
  name: 'Ashley',
  age: 26
};

function personRedefiner (obj, name, age) {
  obj = {
    name: name,
    age: age
  };
}

personRedefiner (person2, 'Joe', 21); // original object not changed

This second example does not modify the original object. I would have to change the function to return the object, then set person2 = personRedefiner(person2, 'joe', 21);

第二个示例不会修改原始对象。我必须更改函数以返回对象,然后设置person2 = personRedefiner(person2,'joe',21);

Why does the first example work but the second example does not?

为什么第一个例子有效但第二个例子没有?

1 个解决方案

#1


0  

In the second example, you're initializing a new object with scope local to the function.

在第二个示例中,您将初始化一个具有该函数本地范围的新对象。

#1


0  

In the second example, you're initializing a new object with scope local to the function.

在第二个示例中,您将初始化一个具有该函数本地范围的新对象。