php - JavaScript Pass Variables Through Reference -
is there equivalent in javascript php's reference passing of variables?
[php]:
function addtoend(&$therefvar,$str) { $therefvar.=$str; } $myvar="hello"; addtoend($myvar," world!"); print $myvar;//outputs: hello world!
how same code in javascript if possible?
thank you!
objects passed as references.
function addtoend(obj,$str) { obj.setting += $str; } var foo = {setting:"hello"}; addtoend(foo , " world!"); console.log(foo.setting); // outputs: hello world!
edit:
- as posted in comments below, cms made mention of great article.
- it should mentioned there no true way pass by reference in javascript. first line has been changed "by reference" "as reference". workaround merely close you're going (even globals act funny sometimes).
- as cms, holyvier, , matthew point out, distinction should made
foo
reference object , reference passed value function.
the following included way work on object's property, make 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!
Comments
Post a Comment