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

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

问题描述

原始类型(数字、字符串等)是按值传递的,但对象是未知的,因为它们都可以是按值传递的(以防我们认为持有对象的变量实际上是一个引用对象)和引用传递(当我们认为对象的变量保存对象本身时).

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 根本不是引用,那么更改 obj1.item 不会对函数外部的 obj1 产生影响.
  • 如果参数是正确的引用,那么一切都会改变.num 将是 100,而 obj2.item 将读取 changed".相反,num 保持 10obj2.item 保持 未更改".
    • If obj1 was not a reference at all, then changing obj1.item would have no effect on the obj1 outside of the function.
    • If the argument was a proper reference, then everything would have changed. num would be 100, and obj2.item would read "changed". Instead, num stays 10 and obj2.item remains "unchanged".
    • 相反,情况是传入的item是按值传递的.但是通过值传递的项目本身是一个引用.从技术上讲,这称为call-by-sharing.

      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.

      实际上,这意味着如果您更改参数本身(如 numobj2),则不会影响输入到范围.但是,如果您更改参数的内部,它会反向传播(与 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天全站免登陆