Skip to content

Instantly share code, notes, and snippets.

@rmg
Created February 7, 2014 19:02
Show Gist options
  • Save rmg/8869460 to your computer and use it in GitHub Desktop.
Save rmg/8869460 to your computer and use it in GitHub Desktop.
Dynamic scoping in JavaScript
name = 'global'; // skip var to make true global in node
var a = { name: 'a' };
var b = { name: 'b' };
// make a global variable 'named' and assing the function to it
// if we just do function named() {} then it is scoped as though we used var
named = function func(/* this, not a real argument */ arg) {
console.log("this:", this.name, "arg:", arg.name);
}
a.named = b.named = named;
named(a); // => this: global arg: a
global.named(a); // => this: global arg: a
named(global); // => this: global arg: global
a.named(b); // => this: a arg: b
a['named'](b); // => this: a arg: b
b.named(global); // => this: b arg: global
// functions are objects and values too!
named.named = named;
named.named(named); // => this: func arg: func
named(named); // => this: global arg: func
// circular reference!
a.named(a.named.named.named) // => this: a arg: func
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment