You should read about closures.
They help to prevent putting all kind of variables public.
so you can wrap it with in a closure, or self-invoking-function, there are
several names and methods, but the basic example used in MooTools is:
(function(){
var private = 'yo';
})();
alert(private); // throws error
But we don't want to put everything privately, but want to make it
public. Fortunately we can just put something on the window object. The
window object is equal to `this` in the browser:
console.log(window == this);
This is also true in closures:
(function(){
this.hello = 'yo';
})();
console.log(window.hello, this.hello, hello); // yo
For better compression you can do something like this:
(function(){
var hello = this.hello = 'yo';
// now we can use hello here, which is private, instead of this.hello every
thime
})();
In 1.3.1 and in PowerTools .call(this) was used. .call and .apply work like
bind, but also execute the function. So here the inner this was set to the
outer this, which was still window. This supposed to fix something in some
fancy environments, but didn't work in node.js after all, since this refers
to something else there and not the global object.
There are also other variants to fix nasty errors with compressing, when the
last ; is forgotten, see this example, which works ok
(function(){
})()
(function(){
})()
but when we compress:
(function(){})()(function(){})()
which errors.
Putting some other char before the (function(){, like a !, ; ~, + or
whatever solves this problem.
I hope this helps you and I've given you some pointers to search further.
On Sun, May 15, 2011 at 8:16 PM, Rolf -nl <[email protected]> wrote:
> Looking at Moo's source and following the syntax and code style rules
> I was (in the past) used to do it like:
>
> var myClass = new Class({
> });
>
> then people started to wrap it and adopted:
>
> (function(){
>
> var myClass = new Class({
> });
>
> })();
>
> or an alternate ending for the wrap (like in cpojer's powertools):
>
> }).call(this);
>
> ryan florence is dropping trailing semi-colons in his (non mootools
> released) js code (which is fine I think, others can disagree) but
> starting code with a semi-colon before every parenthese like:
>
> ;(function(){
> })();
>
> and I also noticed this:
>
> var myClass = this.myClass = new Class({
> });
>
> since when are we also adding this.myClass? What is the benefit, why
> is it important?
>
> Ok, what I'm trying to say is that I see sort of the use of all of
> this and I understand what it does, but I don't fully 'get' the path
> to follow or why I would do it one way or the other.
>
> Maybe someone can enlighten us here on the list or maybe a blog post
> to take away some confusion.
>
>