In javascript, that makes this syntax `(function (window, undfined)) {} (window)` execute

I am trying to figure out how to β€œbind” JavaScript events together, as jQuery does. I found here a question about S.O. it was like my goal, but I don't understand the code in the answer.

Source code

(function( window, undefined ) { ...etc... }(window) 

What does it mean? What is he doing? This reminds me of the JQuery function $(document).ready(){} , but I don’t know why this person wrapped his code in this anonymous function, which passes window and undefined .

My ultimate goal is to figure out how to execute methods on an object by combining methods together like jQuery. I know that jQuery is already doing this, but I consider it primarily for growth as a developer.

+4
source share
2 answers

It defines a function (using a function operator as opposed to a function operator ). The brackets around it ensure that it is treated as an operator, not an operator.

Then it executes it immediately, passing window as an argument.

Essentially, this is the same as:

 var myFunction = function( window, undefined ) { ...etc... }; myFunction(window); 

... but without an intermediate variable.

This has nothing to do with the jQuery-style function chain, where each method effectively ends up with return this (therefore, calling the method for the return value of another method is the same as calling it on the original object).

+3
source

When a function is called with fewer arguments than its signature contains, the return arguments are set to undefined .

Thus, the above is a roundabout way to get the value undefined , even if some crazy person overrides it by saying var undefined= 'hello'; . (In any case, this is illegal in ECMAScript Fifth Edition strict mode, but JavaScript encoders sometimes do some weird things.)

Actually there is no good reason for going into a window like this, though ... the traditional way to get a window , if you cannot rely on window , is to call the function directly and use this .

In any case, this is just defensive coding against the author's pathological JavaScript. This is not something you should worry about when you write your own code (in any case, you cannot stop anything that can ruin their JS environment in any way), and it is not chain-related.

+3
source

All Articles