JavaScript Pass Variables Through Reference

前端 未结 4 883
刺人心
刺人心 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:47

    The other answers/comments describe the situation well enough, but I thought I'd offer and alternative if you need that style of functionality, by using a callback.

    var someText = "asd";
    addToEnd(someText, "fgh", function(val) { someText = val; });
    

    and

    function addToEnd(original, str, setValue)
    {
        setValue(original += str);
    }
    

    but a better solution would be

    var someText = "asd";
    someText = addToEnd(someText, "fgh");
    

    and

    function addToEnd(original, str)
    {
        return original += str;
    }
    

提交回复
热议问题