Sometimes I hear people say \"a reference to a object\" and some say \"a instance of a object\" What is the difference?
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