本文介绍了JavaScript 通过引用传递变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在 JavaScript 中是否有等效的 PHP 变量引用传递?
Is there an equivalent in JavaScript for PHP's reference passing of variables?
[PHP]:
function addToEnd(&$theRefVar,$str)
{
$theRefVar.=$str;
}
$myVar="Hello";
addToEnd($myVar," World!");
print $myVar;//Outputs: Hello World!
如果可能,相同的代码在 JavaScript 中会是什么样子?
How would the same code look in JavaScript if possible?
谢谢!
推荐答案
对象被作为引用传递.
function addToEnd(obj,$str)
{
obj.setting += $str;
}
var foo = {setting:"Hello"};
addToEnd(foo , " World!");
console.log(foo.setting); // Outputs: Hello World!
- 正如在下面的评论中发布的那样,CMS 提到了一个很棒的 文章.
- 应该提到的是,在 JavaScript 中没有真正的方法可以通过引用传递任何东西.第一行已从by reference"更改为as reference".这种变通方法与您将要得到的一样接近(有时甚至全局变量的行为也很有趣).
- 作为 CMS,HoLyVieR 和 Matthew 指出,应该区分
foo
是对对象的引用,该引用通过值传递给函数.
- As posted in comments below, CMS made mention of a great article.
- It should be mentioned that there is no true way to pass anything by reference in JavaScript. The first line has been changed from "by reference" to "as reference". This workaround is merely as close as you're going to get (even globals act funny sometimes).
- As CMS, HoLyVieR, and Matthew point out, the distinction should be made that
foo
is a reference to an object and that reference is passed by value to the function.
以下内容是处理对象属性的另一种方法,使您的函数定义更加健壮.
The following is included as another way to work on the object's property, to make your function definition more robust.
function addToEnd(obj,prop,$str)
{
obj[prop] += $str;
}
var foo = {setting:"Hello"};
addToEnd(foo , 'setting' , " World!");
console.log(foo.setting); // Outputs: Hello World!
这篇关于JavaScript 通过引用传递变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!