Last active
December 10, 2015 19:58
-
-
Save c4urself/4485335 to your computer and use it in GitHub Desktop.
Javascript (mainly) pass-by-value
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// More explicit example of | |
// http://stackoverflow.com/questions/518000/is-javascript-a-pass-by-reference-or-pass-by-value-language | |
// | |
// When you change the `item` property of the object referenced by `obj1`, you are changing the value | |
// of the `item` property that was originally set to 'unchanged'. When you assign `obj2` a value of | |
// {item: 'changed'} you are changing the reference to a new object. This object immediately goes out | |
// of scope when the function exits. | |
function changeStuff(_num, _obj1, _obj2) { | |
_num = _num * 10; | |
_obj1.item = 'changed'; | |
_obj2 = {item: 'changed'}; | |
} | |
var num = 10, | |
obj1 = {}, | |
obj2 = {}; | |
obj1.item = 'unchanged'; | |
obj2.item = 'unchanged'; | |
changeStuff(num, obj1, obj2); | |
console.log(num); // 10 | |
console.log(obj1.item); // "changed" | |
console.log(obj2.item); // "unchanged" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment