The basic form of anonymous functions is(function(){...})();
The parentheses in the front contain the function body, and the parentheses in the back are to pass parameters to the anonymous function and execute immediately.
The function of anonymous functions is to avoid contamination of global variables and conflicts of function names.
No matter when you read the code, you must notice anonymous functions. Sometimes they are called lambdas, sometimes they are anonymous functions, and I think they are not easy to use anyway.
If you don't know what anonymous functions are, here is a quote:
Anonymous functions are functions that are declared dynamically at runtime. They are called anonymous functions because unlike ordinary functions, they do not have function names. — Helen Emerson,
The anonymous function is as follows:
function () { ... code ... } OR (args) => { ... code .. }
Today I'm trying to get everyone to understand the idea of using anonymous functions normally only if they are absolutely necessary. Anonymous functions should not be preferred, and should be used if you know the reason. 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 using anonymous functions:
When you write code, no matter how good you are at typing code, you will always encounter errors. Sometimes, these errors are easily detected, and sometimes they are not easy.
If you know where these errors come from, then the errors are easily found. To find out the error, we use this tool called Stack Track. If you don't understand Stack Tracks, Google gives a great introduction.
Suppose there is a very simple project now:
function start () { (function middle () { (function end () { ('test'); })() })() }
There is a very stupid error in the above code, spelling(). In small projects, this spelling error is not a big problem. If this is a small section of a project with many modules and very large modules, the problem will be big. Assuming that this stupid mistake was not made by you, the new junior engineer will submit the error to the code base before he takes a vacation!
Now, we have to track down. Using our carefully named functions, we get the following stack trace:
Thank you for naming your function, junior developers! Now we can easily track this bug.
But... Once we solve this problem, we will find that there is another bug. This time it was introduced by a more senior developer. This person knows lambdas
As a result, they stumbled upon a bug and our job was to track it down.
Here is the code:
(function () { (function () { (function () { ('test'); })(); })(); })();
Not surprised, the developer also forgot how to spell it! This is a coincidence! Unfortunately, none of them named their functions.
So what will the console output?
OK, we at least have line numbers, right? In this example, it looks like we have about 7 lines of code. What if we deal with a large piece of code? For example, ten thousand lines of code? What should I do if the line number span is so large? If there is a code map file after the code is collapsed, isn't rendering of line numbers useless?
I think the answer to these questions is quite simple, and the answer is: thinking about these will make you feel bad all day long.
readability
Hey, I heard you don't believe it yet. You are still reluctant to leave your anonymous function and have never had a bug. Then I have to apologize to you, you think your code is perfect. Let's take a look at this!
Take a look at the following two codes:
function initiate (arguments) { return new Promise((resolve, reject) => { try { if (arguments) { return resolve(true); } return resolve(false); } catch (e) { reject(e); } }); } initiate(true) .then(res => { if (res) { doSomethingElse(); } else { doSomething(); } ).catch(e => { logError(); restartApp(); } );
This is a very abnormal example, but I believe you already understand what I am going to say. Our method returns a promise, and we use this promise object/method to handle different possible responses.
You might think that a few pieces of code are not difficult to read, but I think they can get better!
What if we remove all the anonymous functions?
function initiate (arguments) { return new Promise(checkForArguments); } function checkForArguments (resolve, reject) { try { if (arguments) { return resolve(true); } return resolve(false); } catch (e) { reject(e); } } function evaluateRes (res) { if (res) { doSomethingElse(); } else { doSomething(); } } function handleError (e) { logError(); restartApp(); } initiate(true) .then(evaluateRes) .catch(handleError);
OK, let's make it clear first: this part of the code is longer, but I think it's not just more readable! Our carefully named functions are different from anonymous functions, and we know what their functions are as soon as we see their names. This avoids obstacles when evaluating code.
This also helps to distinguish the relationship. Unlike creating a method, passing it, and then running logic, the parameters in the second example are given to then, catch just points to the function where everything happens.
There is nothing I can convince you about being more readable. But maybe if you haven't been convinced, I can try the final argument.
Summarize
The above is the reason why I will not use JS anonymous functions introduced to you. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. Thank you very much for your support for my website!