JavaScript是一种传递引用还是按值传递的语言? [英] Is JavaScript a pass-by-reference or pass-by-value language?

查看:131
本文介绍了JavaScript是一种传递引用还是按值传递的语言?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本类型(Number,String等)按值传递,但是对象是未知的,因为它们可以是值传递的(如果我们认为持有对象的变量实际上是一个引用到对象)和传递引用(当我们认为对象的变量持有对象本身时)。

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).

虽然它并不重要结束,我想知道提交传递约定的参数的正确方法是什么。是否有JavaScript规范的摘录,它定义了关于此的语义应该是什么?

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中很有意思。考虑这个例子:

It's interesting in 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);

这会产生输出:

10
changed
unchanged




  • 如果是纯值传递,那么更改 obj1.item 会有对函数外部的 obj1 没有影响。

  • 如果它是纯粹的参考传递,那么一切都会改变。 num 100 ,并且 obj2.item 将会读取已更改

    • If it was pure pass by value, then changing obj1.item would have no effect on the obj1 outside of the function.
    • If it was pure pass by reference, then everything would have changed. num would be 100, and obj2.item would read "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.

      实际上,这意味着如果您更改参数本身(与 num obj2 <一样) / code>),这不会影响输入参数的项目。
      但是如果您更改参数的 INTERNALS ,那么它将传播回来(与 obj1 一样)。

      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. But if you change the INTERNALS of the parameter, that will propagate back up (as with obj1).

      这篇关于JavaScript是一种传递引用还是按值传递的语言?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆