Difference between reference and instance in javascript

后端 未结 8 2084
长情又很酷
长情又很酷 2020-12-23 23:10

Sometimes I hear people say \"a reference to a object\" and some say \"a instance of a object\" What is the difference?

8条回答
  •  星月不相逢
    2020-12-23 23:22

    In javascript a variable is a reference to the actual instance

        // create a new object from the Object constructor
        // and assign a reference to it called `firstObjRef`
        var firstObjectRef = new Object();
    
        // Give the object the property `prop`
        firstObjRef.prop = "im a property created through `firstObjRef`";
    
    
        // Create a second reference (called `secondObjRef`) to the same object
        var secondObjRef = firstObjRef;
        // this creates a reference to firstObjRef,
        // which in turn references the object
    
        secondObjRef.otherProp = "im a property created through `secondObjRef`";
    
    
        // We can access both properties from both references
        // This means `firstObjRef` & `secondObjRef` are the same object
        // not just copies
    
        firstObjRef.otherProp === secondObjRef.otherProp;
        // Returns true
    

    This will also work if you pass a variable to a function:

    
        function objectChanger (obj, val) {
             // set the referenced object;s property `prop` to the referenced
             // value of `val`
             obj.prop = val;
        }
    
        // define a empty object outside of `objectChanger`'s scope
        var globalObject = {};
    
        globalObject === {}; // true
    
        // pass olobalObject to the function objectChanger
        objectChanger(globalObject, "Im a string");
    
        globalObject === {}; // false
        globalObject.prop === "Im a string"; // true
    
    

提交回复
热议问题