This question already has an answer here:
这个问题在这里已有答案:
- Is JavaScript a pass-by-reference or pass-by-value language? 31 answers
JavaScript是传递引用还是按值传递语言? 31个答案
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.
在第二个示例中,您将初始化一个具有该函数本地范围的新对象。