Javascript pass by reference array example
Uses javascript arrays to show how javascript passes by reference for objects.
by Riffic
JavaScript
function arrBuild() {
return [].slice.call(arguments);
}
var myArr = arrBuild(1, "test", 151);
console.log(myArr);
function classBuilder(saveArr) {
var savedArr = saveArr;
var classBuild = function() {
this.getSavedArr = function() {
return savedArr;
};
};
return classBuild;
};
//build the class to pass the reference
var myClass = classBuilder(myArr );
//get a new class which has the saved array reference
var myExample = new myClass();
//displays original values before change
console.log(myExample.getSavedArr() );
//pass the reference again
var testArr = myExample.getSavedArr();
//push a value to test against the original
testArr.push( 'testNew' );
//outputs both the original array var and the new one to show they are the same
console.log("Test Arr from class builder:", testArr );
console.log("Original array modified:", myArr );