The creation of anonymous functions and the analysis of calling methods in js

  • 2020-05-07 19:15:14
  • OfStack

This article analyzes the creation and invocation methods of anonymous functions in js. Share with you for your reference. The specific implementation method is as follows:

An anonymous function is a function without a name, also called a closure function (closures), which allows the temporary creation of a function without a specified name. Most often used as the value of the callback function (callback) parameter, many newcomers are unfamiliar with anonymous functions. So let's analyze 1.

function function name (parameter list){function body; }

If you are creating an anonymous function, it should be:
function(){function body; }

Because it is an anonymous function, there is no argument passed to it.

Why create anonymous functions? When are anonymous functions used? There are two common scenarios for anonymous functions: 1 is a callback function and 2 is a direct execution function.

Callback functions, like the asynchronous operation of ajax, require callback functions. I won't go into that here. About the direct execution function, I see an example:

<script language="javascript">
var a = "a";
(function(){
    var a="b";
    alert(a);
})();
alert(a);
</script>

In the above code, two alert boxes are printed in sequence. The first alert box contains b and the second a. Do you see any benefits? Yes, direct execution of functions limits the scope of variables so that the same variables from different scripts can coexist.

Next, let's take a look at the concepts associated with anonymous functions.

Function declaration (function statement), to use a function, we must first declare its existence. The most common way is to use function statement to define a function, such as:

function abc(){ 
// code to process
}
function abc(){ // code to process }

Of course, your function can take arguments or even return values.

view plaincopy to clipboardprint? 
function abc(x,y){
return x+y;
}
function abc(x,y){ return x+y; }

However, no matter how you define your function, the JS interpreter translates it into an Function object. For example, you define the function number of one of the above examples and enter the following code:

alert(typeof abc);// "function"

Your browser will prompt you that abc is an Function object. So what exactly is an Function object?

Function object

The Function object is an inherent object in JavaScript, and all functions are actually 1 Function object. Let's see if we can create a new function directly from the constructor on the Function object. The answer is yes. Such as:

var abc = new Function("x","y","return x*y;"); 
alert(abc(2,3)); // "6"

I think you now have some idea of how to declare a function. So what is an anonymous function?

declares the anonymous function

As the name implies, an anonymous function is one that has no actual name. For example, let's remove the name of the function in the above example and judge whether 1 is a function:

alert(typeof function(){});// "function" 
alert(typeof function(x,y){return x+y;});// "function"
alert(typeof new Function("x","y","return x*y;"))// "function"
alert(typeof function(){});// "function"
alert(typeof function(x,y){return x+y;});// "function"
alert(typeof new Function("x","y","return x*y;"))// "function"

We can easily see that they are all Function objects, in other words, they are all functions, but they all have one characteristic -- no name. So we call them anonymous functions. However, because they don't have a name, we can't find them. This leads to the problem of how to call an anonymous function.

Call for the anonymous function

To call a function, we must have a method to locate it and reference it. So, we're going to have to find a name for it. Such as:

var abc=function(x,y){ 
return x+y;
}
alert(abc(2,3)); // "5"

The above operation is actually equivalent to defining the function in a different way, which we often encounter. For example, when we set an DOM element event handler, we usually do not give them a name, but give its corresponding event to refer to an anonymous function.

There is another way to call an anonymous function, which is the jQuery fragment we saw -- to enclose the anonymous function with (), followed by a pair of parentheses (containing a list of arguments). Let's look at the following example:

alert((function(x,y){return x+y;})(2,3));// "5" 
alert((new Function("x","y","return x*y;"))(2,3));// "6"

Many people may wonder why this method is called successfully. For those of you who think this app is weird, take a look at the following explanation.

Do you know what the parentheses do? The parentheses combine our expression into blocks, and for every block, for every pair of parentheses, there is one return value. This return value is essentially the return value of the expression in parentheses. So, when we put a 1 pair of parentheses around an anonymous function, what the pair of parentheses actually returns is an Function object for an anonymous function. So, the pair of braces with the anonymous function is just as much a reference as a function with a name. So if you add a list of arguments after the reference variable, you'll get a normal function call.

I don't know if you can understand the above text, if you still can't understand, and look at the following code to try it.

var abc=function(x,y){return x+y;};//  Assign an anonymous function object to abc 
// abc the constructor And anonymous functions constructor 1 The sample. In other words, the implementation of both functions is 1 Kind of.
alert((abc).constructor==(function(x,y){return x+y;}).constructor);

PS: constructor is a function that creates objects. That is, the body of the function represented by the function object.
In general,
is understood as a function object returned by a parenthesized expression, and then the function object can be called as a normal argument list. (an error was made here. Only function expressions cannot call functions directly. function(){alert(1)})() should be equivalent to a=function(){alert(1)}().

closure

What is a closure? A closure is a block of code in a programming language that allows a level 1 function to exist and the free variables defined in the level 1 function to remain unreleased until the level 1 function is released.

How to? It makes me sweat... No, me too (although I understand, it's just a matter of presentation). Let's change a more simple way: closures, is actually one kind of language features, it is to point to the programming language, allowed to function as object, and then can like operating in the object defined in the function instance (local) variable, and these variables can be kept in a function to the function of instance object is destroyed, the other code block can in some way for these instances (local) variable extension and application.

I don't know if this will make it any clearer, but if it doesn't, let's simplify it one more time: a closure is simply a local variable defined in a programming language that allows code to call a function that is already running.

Now let's look at an example:

var abc=function(y){ 
var x=y;// This is a local variable
return function(){
alert(x++);// This is where the closure property is called 1 Of a level function local variable x And operate on it
alert(y--);// The referenced parameter variables are also free variables
}}(5);// Initialize the
abc();// "5" "5"
abc();// "6" "4"
abc();// "7" "3"
alert(x);// An error! " x " Undefined!

At this point, can you tell if the jQuery snippet is closed?

As I understand it. Whether the closure feature is applied, you must determine if the code has the most important element: undestroyed local variables. Obviously, then, anonymous functions without any implementation cannot apply the closure feature. But what if there is an implementation in an anonymous function? It also has to be made sure that its implementation USES those undestroyed local variables. So if you ask yourself what features of jQuery are used in the JS snippet in the opening? So it's just an anonymous function and an anonymous function call. However, it hides the nature of closures and is ready to be applied.

Most common usage:

(function() { 
alert('water');
})();

Of course, parameters can also be taken:
(function(o) { 
alert(o);
})('water');

Want to use chain calls of anonymous functions? Is simple:
(function(o) { 
alert(o);
return arguments.callee;
})('water')('down');

Now that you know the usual anonymous functions, look at the unusual ones:
~(function(){ 
alert('water');
})();// It's kind of cool ~
 
void function(){
alert('water');
}();// Said to be the most efficient ~
 
+function(){
alert('water');
}();
 
-function(){
alert('water');
}();
 
~function(){
alert('water');
}();
 
!function(){
alert('water');
}();
 
(function(){
alert('water');
}());// A little bit of enforcement ~

I hope this article has been helpful to your javascript programming.


Related articles: