one shot anonymous javascript function
by Andy Bulka
HTML
<p>Example of a one shot anonymous javascript function which creates its own scope/namespace when run and gets invoked with some parameters, and returns an object.</p>
<p>Ah of course. Even though we have a function which defines its own scope/namespace whilst it runs (as would a function in any other language), and appears to only communicate with the outside world via its parameters window and jquery...</p>
<pre>
(function($, window, undefined) {
...
})( jQuery, window );
</pre>
<p>this function can still access any global objects that exist at that time. Which means it can access _</p>
<p>This then raises the question of why we bother passing in $, window, undefined since these are all global objects too and perfectly accessible. Unless someone redefines these global objects (unlikely) we could get away with no parameters to this function ! I'm not saying this to criticise the code, only to understand and comment about what's possible.</p>
JavaScript
var x = (function(a, b) {
console.log('hi', a, b, window, undefined, $);
var temp1 = -1;
return {'a':a, 'b':b+20}
})( "andy", 100 );
console.log(x);
// another one shot - inside jquery wrapper
// what does that mean?
$(function() {
console.log('another anon function wrapped in jquery');
});