Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
259 views
in Technique[技术] by (71.8m points)

javascript - JavaScript是按引用传递还是按值传递语言?(Is JavaScript a pass-by-reference or pass-by-value language?)

The primitive types (number, string, etc.) are passed by value, but objects are unknown, because they can be both passed-by-value (in case we consider that a variable holding an object is in fact a reference to the object) and passed-by-reference (when we consider that the variable to the object holds the object itself).(基本类型(数字,字符串等)按值传递,但对象是未知的,因为它们都可以按值传递(如果我们认为保存对象的变量实际上是对对象的引用) )和按引用传递(当我们认为对象的变量包含对象本身时)。)

Although it doesn't really matter at the end, I want to know what is the correct way to present the arguments passing conventions.(尽管最后并没有什么大不了,但我想知道呈现通过惯例的参数的正确方法是什么。)

Is there an excerpt from JavaScript specification, which defines what should be the semantics regarding this?(是否有JavaScript规范的摘录,其中定义了与此相关的语义?)   ask by Danail Nachev translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

It's interesting in JavaScript.(JavaScript很有趣。)

Consider this example:(考虑以下示例:)

 function changeStuff(a, b, c) { a = a * 10; b.item = "changed"; c = {item: "changed"}; } var num = 10; var obj1 = {item: "unchanged"}; var obj2 = {item: "unchanged"}; changeStuff(num, obj1, obj2); console.log(num); console.log(obj1.item); console.log(obj2.item); 

This produces the output:(产生输出:)

10
changed
unchanged
  • If obj1 was not a reference at all, then changing obj1.item would have no effect on the obj1 outside of the function.(如果obj1根本不是引用,则更改obj1.item将对该函数外部的obj1无效。)
  • If the argument was a proper reference, then everything would have changed.(如果该论点是适当的参考,那么一切都会改变。) num would be 100 , and obj2.item would read "changed" .(num100 ,而obj2.item读为"changed" 。)

Instead, the situation is that the item passed in is passed by value.(相反,情况是传入的项目是按值传递的。)

But the item that is passed by value is itself a reference.(但是,按值传递的项目本身就是参考。) Technically, this is called call-by-sharing .(从技术上讲,这称为共享呼叫 。)

In practical terms, this means that if you change the parameter itself (as with num and obj2 ), that won't affect the item that was fed into the parameter.(实际上,这意味着如果您更改参数本身(如numobj2 ),则不会影响输入该参数的项目。)

But if you change the INTERNALS of the parameter, that will propagate back up (as with obj1 ).(但是,如果您更改参数的INTERNALS ,则它将传播回去(与obj1 )。)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...