JavaScript Pass Variables Through Reference

前端 未结 4 874
刺人心
刺人心 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-22 14:55

    In Javascript there is no passing variable by reference like in PHP. There is a possible workaround to do something similar.

    function addToEnd(obj, str)
    {
        obj.value += str;
    }
    
    myVar={value:"Hello"};
    
    addToEnd(myVar, " World");   
    alert(myVar.value); //Outputs: Hello World!
    

    In this example, what happens is that you pass an object to the function and inside of it, you are modifying the object (not the variable, the variable is still pointing to the same object). This is why this is not passing variable by reference has vol7ron incorrectly stated.

提交回复
热议问题