Skip to content

Instantly share code, notes, and snippets.

@zerowidth
Created August 3, 2010 15:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zerowidth/506540 to your computer and use it in GitHub Desktop.
Save zerowidth/506540 to your computer and use it in GitHub Desktop.
js scoping demo (node.js)
var sys = require('sys');
var foo = {
name: 'foo',
bar: function() {
sys.puts('in bar, this is ' + this.name);
setTimeout(this.bar, 1000);
},
baz: function() {
var me = this;
sys.puts('in baz, this is ' + this.name);
setTimeout(function(){ me.baz(); }, 1000);
}
};
foo.bar(); // 'this' scope goes away after one invocation
foo.baz(); // closing over the scope keeps it around
// $ node node_scope_test.js
// in bar, this is foo
// in baz, this is foo
// in bar, this is undefined
// in baz, this is foo
// in baz, this is foo
// in baz, this is foo
// ...^C
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment