diff options
Diffstat (limited to 'anon-func.js')
-rw-r--r-- | anon-func.js | 50 |
1 files changed, 50 insertions, 0 deletions
diff --git a/anon-func.js b/anon-func.js new file mode 100644 index 0000000..c4e3130 --- /dev/null +++ b/anon-func.js @@ -0,0 +1,50 @@ +/* this is an error +function() { + console.log("hello"); +} +*/ + +// current context in this outermost scope +var c = " foobar"; + +// prints nothing, code doesn't execute +(function() { + console.log('hello' + c); +}); + +// () at the end executes declared function +// NOTICE that functions are objects, better yet, first-class objects, since +// they can be assigned to a variable +(function() { + console.log('hello' + c); +})(); + +// prints hello again foobar +(function() { + console.log('hello again' + c); +}).call(this); + +// prints hello again cruel world foobar +(function(par1, par2) { + console.log('hello again' + par1 + par2 + c); +}).apply(this, [" cruel", " world"]); + +// prints 7 and 13 +var f = function() { return 7; }; +var g = (function() { return 13; }); +console.log(f()); +console.log(g()); + +(function() { + // "use strict" cannot be used since 'this' is an undeclared object, it + // exists but only for life of its scope + this.x = "barfoo"; + console.log(x); + console.log(this.x); + + (function() { + // we're lucky here since js searches for x in higher scopes + console.log(x); + console.log(x); + })(); +})(); |