javascript 将字符串传递给函数是按值复制还是按引用传递?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15664372/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Does passing a string to a function copy it by value or pass it by reference?
提问by dreta
Since strings in JavaScript are basic types, does passing a string to a function create a local copy of it? I'm wondering about this since you can't modify strings after they've been created, so it would seem illogical that JavaScript VMs wouldn't just pass the string's address to the function internally.
由于 JavaScript 中的字符串是基本类型,将字符串传递给函数是否会创建它的本地副本?我对此感到疑惑,因为您无法在创建字符串后对其进行修改,因此 JavaScript VM 不只是在内部将字符串的地址传递给函数似乎是不合逻辑的。
If anybody is going to tell me that i shouldn't worry about this (this happens a lot when talking to web developers), I'm working on HTML5 games and garbage collection is a major concern, so i really need to know.
如果有人要告诉我我不应该担心这个(在与 Web 开发人员交谈时经常发生这种情况),我正在开发 HTML5 游戏,垃圾收集是一个主要问题,所以我真的需要知道。
采纳答案by laktak
The string will be passed by reference.
字符串将通过引用传递。
A string is not mutable so whenever you try to change it you get a new string (eg. by doing value+="more"
).
字符串不是可变的,因此每当您尝试更改它时,您都会得到一个新字符串(例如,通过执行value+="more"
)。
Also see: What does immutable mean?
另请参阅:不可变是什么意思?
@T.J. Crowder: by value vs by ref - if you are looking at the language definition you are correct. However I don't think there is an implementation that actually creates a copy of the string because it would be incredibly slow. Also since strings are immutable primitives there is no need to copy them since they can't change.
@TJ Crowder:按值与按引用 - 如果您正在查看语言定义,那么您是正确的。但是我不认为有一个实现可以实际创建字符串的副本,因为它会非常慢。此外,由于字符串是不可变的原语,因此无需复制它们,因为它们无法更改。
回答by T.J. Crowder
I believe the specification is silent on this point. However, it would be a truly idiotic implementation that passed the actual content of the string rather than passing a reference to that content in memory, even if strings are theoretically "primitives". I suspect most implementations treat "primitive" strings much as they treat object references (in this regard, obviously not in some others, such as ===
), but just not with the Object
trappings.
我相信规范在这一点上是沉默的。然而,这将是一个真正愚蠢的实现,它传递字符串的实际内容而不是传递对内存中该内容的引用,即使字符串理论上是“原始”。我怀疑大多数实现都像对待对象引用一样对待“原始”字符串(在这方面,显然不是在其他一些实现中,例如===
),但只是不带有Object
装饰。