简体   繁体   English

将字符串传递给函数是按值复制还是通过引用传递?

[英]Does passing a string to a function copy it by value or pass it by reference?

Since strings in JavaScript are basic types, does passing a string to a function create a local copy of it? 由于JavaScript中的字符串是基本类型,将字符串传递给函数是否会创建它的本地副本? 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 VMs不会仅仅将字符串的地址传递给函数内部似乎是不合逻辑的。

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. 如果有人要告诉我我不应该担心这个问题(与网络开发人员交谈时会发生这种情况),我正在研究HTML5游戏和垃圾收集是一个主要问题,所以我真的需要知道。

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? 另见: 不可变的意思是什么?

@TJ Crowder: by value vs by ref - if you are looking at the language definition you are correct. @TJ Crowder:通过值与参考 - 如果您正在查看语言定义,那么您是正确的。 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. 此外,由于字符串是不可变的原语,因此无需复制它们,因为它们无法更改。

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陷阱。

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

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