trunikov wrote:
> I've taken a look inside the jquery (core) library. I saw there strange function declaration:
First of all, you might see a lot of strange things there! The jQuery
team goes through some interesting gymnastics to reduce code size,
sacrificing readability for brevity. Unless you're already fairly
experienced, I would not suggest the jQuery core as a good model of
how to write your own code. If you are, you might find some
interesting tricks in there. But that said, this is a common idiom,
although I think you misquote it:
> (function( window, undefined ) {
> // bla bla bla
> })();
I imagine that it actually reads:
| (function( window, undefined ) {
| // bla bla bla
| })(this);
^^^^
The `this` parameter here is used so that the `window` parameter
inside the function is a reference to the global object. In many
situations, it already is, but this technique enforces that.
> Tell me please what is a goal to define last parameter as 'undefined'?
> How does it work?
One silly flaw in Javascript that would probably have been removed had
the language not been standardized so quickly is that `undefined` is
not a keyword like `null`. It is simply a global property. Arbitrary
code can overwrite it. So a library like jQuery that's operating in a
very heterogeneous environment cannot assume that no other code has
overwritten that property. This is one way to restore it. Inside the
function, `undefined` is now pointing to the value of the second
parameter passed to the function. Since we don't pass a parameter
there, the value is undefined, exactly what we want the `undefined`
property to represent. Note that this does *not* override the global
property; it simply shadows it. Outside this function, everything
reverts to the way it was (except that any functions which close over
`undefined` will also have the shadowing version [and if that doesn't
make any sense to you, don't worry about it for now.])
There are other ways this could be done, but this one is common, and I
don't see any major flaws with it? Other opinions?
-- Scott