Created
August 3, 2010 15:20
-
-
Save zerowidth/506540 to your computer and use it in GitHub Desktop.
js scoping demo (node.js)
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
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