简体   繁体   English

javascript函数作用域如何与参数一起使用?

[英]How does javascript function scope work with arguments?

What doesn't the 2nd console.log below return 2? 下面的第二console.log返回2是什么? Is it because inside the function scope when I assign thing = thing + 1 , the assignment of thing is just another variable? 是不是因为功能范围内时,我给你thing = thing + 1 ,的分配thing仅仅是另一个变量? It's no longer referring to the original thing argument that was passed in? 它不再是指传入的原始thing参数?

function change(thing) {
  thing = thing + 1;
  return thing;
}

let a = 1

console.log(change(a)) //2
console.log(a)         //1

That's because in javascript when you pass primitive types to a function like "string" or "number" only a copy is passed, if it were an object or an array then the value would change because those types are passed by reference, for example: 那是因为在javascript中,当您将原始类型传递给诸如“ string”或“ number”之类的函数时,仅传递一个副本,如果它是对象或数组,则值将发生变化,因为这些类型是通过引用传递的,例如:

 function change(thing) { thing.value = thing.value + 1; return thing; } let a = {value: 1}; console.log(change(a)) console.log(a) 

Javascript always pass by value so changing the value of the variable never changes the underlying primitive ( String or number ). Javascript总是按值传递,因此更改变量的值永远不会更改基础基元( String或number )。

Pass by Reference happens only for objects. 通过引用传递仅对对象发生。 In Pass by Reference, Function is called by directly passing the reference/address of the variable as the argument. 在“按引用传递”中,通过直接传递变量的引用/地址作为参数来调用函数。 Changing the argument inside the function affect the variable passed from outside the function. 在函数内部更改参数会影响从函数外部传递的变量。 In Javascript objects and arrays follows pass by reference. 在Javascript中,对象和数组遵循引用传递。

function callByReference(varObj) { 
  console.log("Inside Call by Reference Method"); 
  varObj.a = 100; 
  console.log(varObj); 
} 
let varObj = {a:1};
console.log("Before Call by Reference Method"); 
console.log(varObj);
callByReference(varObj) 
console.log("After Call by Reference Method"); 
console.log(varObj);

Output will be : 输出将是:

Before Call by Reference Method 通过引用方法调用之前

{a: 1} {a:1}

Inside Call by Reference Method 通过引用方法进行内部调用

{a: 100} {a:100}

After Call by Reference Method 通过引用方法调用之后

{a: 100} {a:100}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM