JavaScript 在函数调用时为变量属性设置值

标签 javascript function variables pass-by-reference pass-by-value

我发现有两种方法可以在函数调用时更新变量属性值

示例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/

相关文章:

c# - 是否可以在变量名的名称中使用变量号?

java - 做一个运行代码的网站

javascript - 使 jsfiddle 适应工作网页 knockout

c# - 使用动态值构造的名称定义对象

c - 用c执行linux命令

function - F# 将(自定义)类型分配给函数

c++ - 如何从 extern "C"函数访问类变量?

javascript - 折叠中使用的模运算符的单位元

javascript - 单击提交后平滑滚动到 DIV

c++ - 函数在特定时间内消耗墙时间