Home >Web Front-end >JS Tutorial >(Reprint) Anonymous functions, function literals and closures in JavaScript_javascript skills

(Reprint) Anonymous functions, function literals and closures in JavaScript_javascript skills

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOriginal
2016-05-16 19:13:431023browse

Original source: http://www.dnew.cn/post/196.htm

Let’s first look at the following writing methods

1.function f(x){return x*x; };f(x);

2.(function(x){return x*x;})(x);

3.(function(x){return x*x ;}(x));

We should all be familiar with the first type, which is the writing method we often use. The second and third methods are all ways of writing anonymous functions.

-------------------------------------------------- ------------------------------------

The second
can be like this Understanding:

var f=function(x) {return x*x;};f()

Then if we don’t refer to the function through the variable f, it is

function (){}()

However, this is definitely wrong, just like

var f=1 2;
f=f*0;

and

var f=1 2*0;


The results are different.
The only way to get the correct result is:

f=(1 2)*0;

That is, the program block must be clearly identified, that is:

( function(){})()


You may have questions: Do the brackets "()" play a role in identifying code blocks?
We can use JavaScript’s built-in functions to check it!
Give the simplest example:

alert(4)

This code will prompt that the content is "4"
Change it to this
(alert)( 4)

You can see that the execution effect is the same as the previous code.

This form of function execution is also used by many JavaScript frameworks.

-------------------------------------------------- ------------------------------------

The third one, if you have used it If you look at the jsvm framework, you will find that the code inside uses this form.
How to explain the third situation?
In order to understand how the browser understands this writing, we can use the error console function of Mozilla Firefox.
Insert an error code in the code. The code snippet is as follows:

(function(s){s s}(1)).splice();

Open Mozilla Firefox’s error control Taiwan, you can see the following error message

error: (function (s) {})(1) has no properties
Source file: file:///C:/Documents……. html
line: 18

It can be considered that the browser treats code like
(function(s){s s}(1))
according to

(function ( s) {s s})(1)
to analyze.


----------------------------------------- ---------------------------------------

At this point you may have Such understanding:

function f(x){return x*x;};f(x);==(function(x){return x*x;})(x);==( function(x){return x*x;}(x));


But they are still different,
First of all, for other functions like the second and third forms, It is impossible for the code to call the defined function. There is a saying that such a function is called an anonymous function or a function literal.
Secondly, for the functions executed in the second and third forms, the intermediate variables will not pollute the global namespace. You can regard the intermediate code as a pure sub-process call.
Of course, closures can be easily implemented using the latter two forms of function definitions.
看一个例子:

/*
http://jibbering.com/faq/faq_notes/closures.html(Dnew.CN注)
A global variable - getImgInPositionedDivHtml - is declared and
  assigned the value of an inner function expression returned from
  a one-time call to an outer function expression.

  That inner function returns a string of HTML that represents an
  absolutely positioned DIV wrapped round an IMG element, such that
  all of the variable attribute values are provided as parameters
  to the function call:-
*/
var getImgInPositionedDivHtml = (function(){
   /* The - buffAr - Array is assigned to a local variable of the
      outer function expression. It is only created once and that one
      instance of the array is available to the inner function so that
      it can be used on each execution of that inner function.

      Empty strings are used as placeholders for the date that is to
      be inserted into the Array by the inner function:-
   */
   var buffAr = [
       '

       '',   //index 1, DIV ID attribute
       '" style="position:absolute;top:',
       '',   //index 3, DIV top position
       'px;left:',
       '',   //index 5, DIV left position
       'px;width:',
       '',   //index 7, DIV width
       'px;height:',
       '',   //index 9, DIV height
       'px;overflow:hidden;\">(Reprint) Anonymous functions, function literals and closures in JavaScript_javascript skills       '',   //index 11, IMG URL
       '\" width=\"',
       '',   //index 13, IMG width
       '\" height=\"',
       '',   //index 15, IMG height
       '\" alt=\"',
       '',   //index 17, IMG alt text
       '\">'
   ];
   /* Return the inner function object that is the result of the
      evaluation of a function expression. It is this inner function
      object that will be executed on each call to -
      getImgInPositionedDivHtml( ... ) -:-
   */
   return (function(url, id, width, height, top, left, altText){
       /* Assign the various parameters to the corresponding
          locations in the buffer array:-
       */
       buffAr[1] = id;
       buffAr[3] = top;
       buffAr[5] = left;
       buffAr[13] = (buffAr[7] = width);
       buffAr[15] = (buffAr[9] = height);
       buffAr[11] = url;
       buffAr[17] = altText;
       /* Return the string created by joining each element in the
          array using an empty string (which is the same as just
          joining the elements together):-
       */
       return buffAr.join('');
   }); //:End of inner function expression.
})();
/*^^- :The inline execution of the outer function expression. */
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn