我发现有两种方法可以在函数调用时更新变量属性值
示例1:
function bar( arg ) {
return arg + 1;
}
var foo = {
num: 1
};
foo.num = bar( foo.num );
console.log( foo.num );
示例2:
function bar( arg ) {
arg.num = arg.num + 1;
}
var foo = {
num: 1
};
bar( foo );
console.log( foo.num );
我想知道每个方法调用的正确命名约定是什么。
还有谁能解释一下,如何在封闭函数操作中更新原始变量值,如示例 2 所示?
最佳答案
Primitive parameters (such as a number) are passed to functions by value; the value is passed to the function, but if the function changes the value of the parameter, this change is not reflected globally or in the calling function.
If you pass an object (i.e. a non-primitive value, such as Array or a user-defined object) as a parameter and the function changes the object's properties, that change is visible outside the function. Source : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions
在 javascript 中,对象是通过引用传递的,因此当您将对象传递给函数时,您传递的是内存引用,而不是内存引用复制
。
因此,当您更新函数中的值时,它会更新引用值。
function bar(arg) {
arg.num = arg.num + 1;
}
var foo = {
num: 1
};
bar(foo);
console.log(foo.num);
当您传递原始值
时,它是通过值
传递的。它传递值的副本
,因此您在 close 函数中所做的任何更改都不会影响原始值。
function bar(arg) {
arg = arg + 1;
}
var foo = 1
bar(foo);
console.log(foo);
关于JavaScript 在函数调用时为变量属性设置值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53682688/