Created
May 29, 2011 16:38
-
-
Save mkuklis/997928 to your computer and use it in GitHub Desktop.
JavaScript passed by value or reference
This file contains hidden or 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
// primitives are passed by value | |
var a = 4; | |
function fn1(val) { | |
val = 5; | |
} | |
fn1(a); | |
alert(a) // still 4 | |
// objects are passed by reference | |
var o = {a: 4}; | |
function fn2(obj) { | |
obj.a = 5; | |
} | |
fn2(o); | |
alert(o.a) // changed to 5 | |
// functions loose their context | |
var o = {a: 4}; | |
o.prototype.change = function () { | |
this.a = 5; | |
} | |
function f3(fn) { | |
fn(); | |
} | |
f3(o.change); | |
o.a // still 4 because change executed in different context | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment