Skip to content

Instantly share code, notes, and snippets.

@mkuklis
Created May 29, 2011 16:38
Show Gist options
  • Save mkuklis/997928 to your computer and use it in GitHub Desktop.
Save mkuklis/997928 to your computer and use it in GitHub Desktop.
JavaScript passed by value or reference
// 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