Testing Reference vs Value

node v0.12.18
version: 1.0.0
endpointsharetweet
var someFunction = function() { var someArray = []; var addToArray = function(thing) { someArray.push(thing); } var addToArrayBroken = function(thing) { someArray = someArray.concat([thing]); } var getSomeArray = function() { return someArray; } return { addToArray: addToArray, addToArrayBroken: addToArrayBroken, someArray: someArray, getSomeArray: getSomeArray } } var someService;
someService = someFunction(); someService.addToArray('a'); someService.addToArray('b'); someService.someArray;
someService = someFunction(); someService.addToArrayBroken('a'); someService.addToArrayBroken('b'); someService.someArray;
What?! Shouldn't this also be ['a', 'b']? Nope! Javascript passes by reference. The addToArrayBroken() actually creates a new array, while the returned object (since it has already been created at this point) points to the original, still empty array. We can fix this by using the encapsulation, i.e. changing the value of someArray WILL change the value in that scope, so if we add a function to reference the scope, we can get the changed value with relatively little extra work.
someService = someFunction(); someService.addToArray('a'); someService.addToArray('b'); someService.getSomeArray();
someService = someFunction(); someService.addToArrayBroken('a'); someService.addToArrayBroken('b'); someService.getSomeArray();
Loading…

no comments

    sign in to comment