Current location - Quotes Website - Personality signature - How to use JS anonymous function
How to use JS anonymous function
What I brought to you this time is how to use the JS anonymous function, and what are the precautions for using the JS anonymous function. The following is an actual case. Let's have a look.

The basic form of anonymous function is (function(){...}) ();

The front bracket contains the function body, and the back bracket is to pass the parameters to the anonymous function and execute it immediately.

The function of anonymous function is to avoid the pollution of global variables and the conflict of function names.

Whenever you read code, you must pay attention to anonymous functions. Sometimes they are called lambda, sometimes they are anonymous functions. I don't think they work well anyway.

If you don't know what an anonymous function is, here is a famous saying:

Anonymous functions are functions that are dynamically declared at runtime. They are called anonymous functions because, unlike ordinary functions, they have no function names. -Helen Emerson, Helephant.com

The form of anonymous function is as follows:

Function () {... Password ...}

operational research

(args)= & gt; {... password ...}

I try to make you understand that anonymous functions are usually used only when absolutely necessary. Anonymous functions should not be the first choice, and should be used when the reason is known. When you understand this idea, your code will become more concise, easier to maintain and easier to track bugs. Let's start with three reasons to avoid anonymous functions:

When you write code, no matter how good you are at typing code, you will always encounter mistakes. Sometimes these mistakes are easy to find, and sometimes they are not.

If you know where these mistakes come from, it is easy to be found. To find out the error, we use this tool called stack trace. If you don't know the stack trace, goole gives a good introduction.

Suppose you have a very simple project now:

Function start () {

(Function middle () {

(function end () {

console . LG(' test ');

})()

})()

}

There is a very stupid mistake in the above code, spelling error (console.log). This spelling mistake is not a big problem in small projects.

If this is a small part of a very large project with many modules, the problem is big. Assuming you didn't make this stupid mistake, the new junior engineer will submit this mistake to the code base before taking a vacation!

Now, we must track it. Using our veritable function, we get the following stack trace:

Thank you junior developers for naming their functions! Now we can easily track this error.

But .. once we solve this problem, we will find another bug. This time it was introduced by a more experienced developer. This man knows Landas.

As a result, they found a bug by accident, and our job is to trace it.

The code is as follows:

(Function () {

(Function () {

(Function () {

console . LG(' test ');

})();

})();

})();

Not surprisingly, developers also forgot how to spell console.log! What a coincidence! Unfortunately, they didn't name their functions.

So what will the console output?

Well, at least we have a phone number, right? In this example, we seem to have about 7 lines of code. What if we deal with a large piece of code? Like ten thousand lines of code? What if the line number spans so much? If there is a code mapping file after the code is folded, is it useless to render the line number at all?

I think the answers to these questions are quite simple, and the answer is: thinking about them all day will make your heart particularly bad.

readability

Gee, I heard you still don't believe it. You are reluctant to part with your anonymity function, and there has never been a bug. Then I owe you an apology. You think your code is perfect. Let's see this!

Please look at the following two pieces of code:

Function initiate (parameter)

Return new commitment ((resolve, reject) =>{

Try {

If (parameter) {

Returns resolve (true);

}

return resolve(false);

} catch (e) {

Reject (e);

}

});

}

Start (true)

. Then (res =>{

if (res) {

doSomethingElse();

} Otherwise {

do something();

}

).catch(e = & gt; {

Log error (e-mail);

restartApp();

}

);

This is a very abnormal example, but I believe you have understood what I want to say. Our method returns a promise, and we use this promise object/method to handle different possible responses.

You may think that a few pieces of code are not difficult to read, but I think it can be better!

What happens if we delete all anonymous functions?

Function initiate (parameter)

Return a new commitment (check parameters);

}

Function check of parameters (solution, rejection) (

Try {

If (parameter) {

Returns resolve (true);

}

return resolve(false);

} catch (e) {

Reject (e);

}

}

Function evaluator (RES)

if (res) {

doSomethingElse();

} Otherwise {

do something();

}

}

Error in function handle (e)

Log error (e-mail);

restartApp();

}

Start (true)

. Then (evaluator)

. catch(handle error);

Ok, let's be clear: this part of the code is longer, but I think it is not only more readable! Our carefully named functions are different from anonymous functions, as long as we know what their functions are as soon as we see their names. This avoids the obstacles of evaluating the code.

This also helps to distinguish relationships. Unlike creating a method, passing it, and then running the logic, in the second example, parameters are given to then, and catch is just a function that points to everything happening.

I have nothing to convince you that it is more readable. But if you don't believe me, I can try the last argument.

I believe you have mastered the method after reading this case. For more exciting, please pay attention to other related articles on Gxl!

Recommended reading: