Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why wrap every prototype "class" object with an anonymous function in JS?

Tags:

javascript

Looking at this JS code by David Fowler he wraps every "class" with an anonymous self executing method where he sends in jQuery and window. I get that this is a way for ensuring that $ and window are actually the global jQuery and winndow variables you'd expect them to be.

But isn't this a bit over-protective? Should you protect yourself from someone else changing the $ and window variable - is there actually code that does that, and if so why? Also, are there other advantages to wrapping everything like this?

like image 271
Riri Avatar asked Sep 14 '12 09:09

Riri


2 Answers

If I remember correctly there are some other libraries than jQuery using the $.

like image 132
Whiskas Avatar answered Sep 20 '22 09:09

Whiskas


The concept of using function context to create local / function scopes is all about to protect your own code. This especially makes sense if you expect your Javascript code to run in an environment where multiple other (maybe even unknown) scripts may get loaded.

So, if some other Javascript code which got load before your own, assigns window.$ with some other value (it might load the prototype framework for instance), then your code is already screwed if you try to access jQuery specific things.

Another point there is the "a--hole"-effect. Someone creates a line like

window.undefined = true;

...
Now, all your checks against undefined will pretty much fail. But by explicitly creating those variables/parameters and filling them with the values you expect, you can avoid all those problems.

(function(win, doc, $, undef) {
}(window, window.document, jQuery));
like image 32
jAndy Avatar answered Sep 19 '22 09:09

jAndy