Call by reference, value, and name

前端 未结 5 868
陌清茗
陌清茗 2020-12-20 16:46

I\'m trying to understand the conceptual difference between call by reference, value, and name.

So I have the following pseudocode:

foo(a, b, c)
{
           


        
5条回答
  •  无人及你
    2020-12-20 17:39

    in javascript :

    1. primitive type variable like string,number are always pass as pass by value.
    2. Array and Object is passed as pass by reference or pass by value based on these condition.

      • if you are changing value of that Object or array with new Object or Array then it is pass by Value.

        object1 = {item: "car"}; array1=[1,2,3];

      here you are assigning new object or array.you are not changing the value of property of old object.so it is pass by value.

      • if you are changing a property value of an object or array then it is pass by Reference.

        object1.item= "car"; array1[0]=9;

      here you are changing a property value of old object.you are not assigning new object or array to old one.so it is pass by reference.

    Code

        function passVar(object1, object2, number1) {
    
            object1.key1= "laptop";
            object2 = {
                key2: "computer"
            };
            number1 = number1 + 1;
        }
    
        var object1 = {
            key1: "car"
        };
        var object2 = {
            key2: "bike"
        };
        var number1 = 10;
    
        passVar(object1, object2, number1);
        console.log(object1.key1);
        console.log(object2.key2);
        console.log(number1);
    
    Output: -
        laptop
        bike
        10
    

提交回复
热议问题