Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Why not use JS anonymous functions

2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains "Why not use JS anonymous functions". The explanation in this article is simple and clear and easy to learn and understand. Please follow the editor's train of thought to study and learn "Why not use JS anonymous functions".

If you don't know what an anonymous function is, here's a quote:

An anonymous function is a function that is dynamically declared at runtime. They are called anonymous functions because, unlike ordinary functions, they do not have function names.  -  Helen Emerson, Helephant.com

The anonymous function takes the following form:

Function () {... Code...} OR (args) = > {. Code.. }

Today I'm trying to make you understand the idea of using anonymous functions only when absolutely necessary. An anonymous function should not be *, and you should know why you use it. When you understand this idea, your code will become more concise, easier to maintain, and easier to track bug.

Start with three reasons to avoid using anonymous functions:

No matter how good you are at writing code, mistakes are inevitable. Sometimes these mistakes are easy to detect, and sometimes they are not.

If you know where these errors come from, they can be easily detected. In order to find errors easily, we use this tool called stack trace. If you don't know the stack trace, goole gives a great introduction.

Suppose you now have a very simple project:

Function start () {(function middle () {(function end () {console.lg ('test');}) ()}) ()}

There is a very stupid mistake in the above code, a spelling error (console.log). In a small project, this spelling mistake is not a big problem. If this is a small section of a project with a lot of modules and a very large one, it will be a big problem. Assuming you didn't make this stupid mistake, the new junior engineer will submit the mistake to the code base before he goes on vacation!

Now, we have to track down. Using our carefully named function, 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 about lambdas (anonymous functions) and uses them a lot in his code. As a result, they stumbled upon a bug, and our job is to track it.

Here is the code:

(function () {(function () {(function () {console.lg ('test');}) ()

Not surprisingly, the developer also forgot how to spell console.log! What a coincidence! Unfortunately, none of them named their functions.

So what will the console output?

Well, at least we have a line number, right? In this example, it looks like we have about seven lines of code. What if we deal with a large piece of code? Like 10,000 lines of code? What should I do if the line number has such a large span? If there is a code map file after the code is folded, is it useless to render the line number at all?

I think the answer to these questions is quite simple: thinking about it will make you miserable all day.

Readability

Why, I hear you still don't believe it. You are still obsessed with your anonymous functions, and bug has never happened. It's my fault. Your code is complete. But let's see this!

Take a look at the following two pieces of code:

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 (e.message); restartApp ();})

This is a very abnormal example, but I'm sure you already know what I'm going to say. We reverse a promise method, and we use this promise object / method to handle different responses.

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

What if we get rid of 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 (e.message); restartApp ();} initiate (true). Then (evaluateRes) .catch (handleError)

Okay, let's be clear: this part of the code is longer, but I don't think it just adds readability! Our carefully named functions are different from anonymous functions, as soon as we see their names, we know what their functions are. This avoids psychological barriers when evaluating code.

It also helps to distinguish the relationship between them. Instead of creating a method, passing it, and then running the logic, the arguments in the second example are given to then,catch and simply point to the function where everything happens.

I have nothing more to convince you about being more readable. But maybe if you haven't been convinced, I can try the argument.

Reusability

Have you noticed the previous example? The scope of the function in the previous example has changed from arguments and initialization functions to making all functions available.

It is difficult to reuse anonymous functions in your application when you use them.

Reusability will no longer exist, and eventually you will write repetitive code over and over again. As we have seen, the less code is written, the less Bug is introduced, and the less content users have to load. Everyone will benefit from it!

In contrast, named functions can be used globally without having to be passed around like variables. Your code will be more reusable.

Is there any merit in anonymous functions?

Yes. Although I hate to admit it, sometimes using anonymous functions is a choice.

Const stuff = [{hide: true, name: 'justin'}, {hide: false, name:' lauren'}, {hide: false, name: 'max'},]; const filteredStuff = stuff.filter (s = >! s.hide)

The anonymous function s = >! s.hide in the above code is so simple that it doesn't have any effect on others even if it can't be used anywhere else, and it can display stack calls in stuff.filter. If you want to reuse this code, * reuse the entire code:

Function filterByHide (array) {return array.filter (item = >! item.hide);}

Sometimes you want to encapsulate all your code in anonymous functions to ensure that the global scope is not contaminated.

(() = > {. Your code here.}) ()

There's really nothing wrong with having an anonymous function in the stack space. It is painful to have no code reuse, because the purpose of integrity is to keep the method contained.

Thank you for reading, the above is the content of "Why not use JS anonymous functions". After the study of this article, I believe you have a deeper understanding of why you do not use JS anonymous functions, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report