JavaScript Pass Variables Through Reference

前端 未结 4 924
刺人心
刺人心 2021-01-22 14:16

Is there an equivalent in JavaScript for PHP\'s reference passing of variables?

[PHP]:

function addToEnd(&$theRefVar,$str)
{
    $theRefVar.=$str;
}
$myVar=\"H         


        
4条回答
  •  無奈伤痛
    2021-01-22 14:44

    Objects are 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 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!
    

提交回复
热议问题