Skip to content

Instantly share code, notes, and snippets.

@zhannes
Created November 30, 2012 16:49
Show Gist options
  • Save zhannes/4176909 to your computer and use it in GitHub Desktop.
Save zhannes/4176909 to your computer and use it in GitHub Desktop.
javascript scoping - 1
// js scoping primer
// util
var _log = function(){
var slice = [].slice,
args = slice.call(arguments),
len = args.length,
i = 0;
for(;i<len;i++) console.log(args[i])
};
/* #########################
1 - SCOPE - GLOBAL
in global scope, defining a variable or a function will create a property on this/window/self
*/
var a = 'foo';
_log( window.a ) // 'foo'
_log( this.a ) // 'foo'
_log( window === this ) // true
_log( self === this ) // true. Be careful with self.
// use var inside a function to avoid creating globals
function b(){
var c = 'foo'; // local
c2 = 'danneh'; // define without var keyword, will be global
_log( window.c ) // undefined
_log( window.c2 ) // 'danneh'
}
b();
// BUT, the function itself is still global
_log( b === window.b )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment