Home Web Front-end JS Tutorial Anonymous functions are a double-edged sword, with advantages and disadvantages

Anonymous functions are a double-edged sword, with advantages and disadvantages

Jun 30, 2017 am 09:29 AM
use function Anonymous

As a functional programming language, you can imagine the important position and huge role of functions in JavaScript. But while it provides great convenience, it also inevitably brings huge problems.

Anonymous functions are a double-edged sword. They make functional programming languages ​​more perfect and make the code more difficult to read. You should know that anonymous functions come at a huge cost of semantics.

If a function does not have a name, it may not matter, and it will lose its meaning in most scenarios. The name of the function is the same as your name, your friend's name, and the name of your pet. It is important, otherwise why would you write it.

There is huge value in using named functions even in the most unnecessary places

You can probably just Enumerate many scenarios to prove the convenience of anonymous functions. It is undeniable that some scenarios undoubtedly have some truth, but most people use this as a starting point and do not do good things for small things. For example, there are many examples of

Array.some, Array.forEach, String.replace

. We can also confidently say that they do not need to use named functions. It is better to use anonymous functions. It’s convenient, and everyone does it. But don't forget that some, forEach, and replace themselves already have broad semantics. But you can still go one step further:

1.Array.some, the broad semantics is to find out whether there is some in the array, but what exactly is some?

2.Array.forEach, the broad semantics is traversal. Array provides countless functions for traversal. Why did you choose forEach instead of map, every, etc.?

3.String.replace, the broad semantics is replacement, but what exactly is it replaced with?

Code is written for people to read,

1. Can you not let me read your code and guess or deduce what you want to find out from the array? Is there an integer? , is there a null value?

2. Can you tell me directly through the function name what you want to do by traversing this array?

3. Can you tell me what you want to replace directly through the function name?

As a simple example, find out whether there is an integer price in the price array. isInteger may be an existing public function. If not, you will have it. It is concise and easy to read. When reading the main process, some codes do not need to be read. isInteger is such a code. What if there is an error? isInteger is testable and easy to test. If you are worried, perform unit testing on it. You may have noticed that with a small change, part of the code has become testable. Even though this isn't a public function, it's neater and more testable to write it as a named function.

var isAnyInteger = priceArr.some(Common.isInteger.bind(Common));

These are very extreme examples where anonymous functions can be written directly, but it is obvious that they can See, they can also be treated as boundaries of named functions, that is, writing named functions will do no harm and will only be better.

No matter how simple the code is, it is necessary to distinguish between architecture and implementation

Another hard-hit area is the then function, the anonymous function The code cannot be uglier. Even if everyone writes it this way, you should understand that you cannot write it this way. The correct posture should be written like this. Take the display order as an example:

/*
 * name        : getOrder
 * description : 获取订单数据 */function getOrder()
{//{{{var url = 'https://www.qunar.com/getOrder';//假如收集参数比较费劲,应该用一个函数专门去收集参数var params = getOrderParams();//假如参数体比较庞大,应该先将其赋予一个变量var params = {
        orderNo:'248663058'};//无论如何,现将参数赋予变量你都将获得在这里打印变量方便调试的便利console.log('getOrder url & params:', url, params);return $.post(url, params);
}//}}}/*
 * name        : renderOrder
 * description : 拿订单,拿到就在页面上展示出来,拿不到就告诉用户为什么没拿到 */function renderOrder()
{//{{{//高级函数,只安排工作,不自己实现//getOrder() 对该函数来说是不可见的,它要的只是订单数据,偷得抢的都可以    getOrder().then(render, remindUser);
}//}}}function render()
{//{{{}//}}}function remindUser()
{//{{{}//}}}
Copy after login

Of course, You may think that renderOrder is useless, and is just the same as a leader who only takes a salary and does not work. Wouldn’t it be enough to write then after $.post?

No, if one day the order can be obtained both locally and from the local cache, then getOrder will be upgraded to a sub-advanced function, which manages two functions getOrderFromServer and getOrderFromCache

If There are some things to do before or after getting the order, then renderOrder can handle it calmly.

Don’t even think about the word over-design. Most people don’t have this ability, so there is no need to worry about it.

You have been a senior architect from the beginning but just write code part-time

You can clearly see that, The extensive use of named functions makes the code structure very clear. Anyone can easily understand the main process. Anyone can easily implement each named function. What is to be implemented has been clearly written in the function name.

These named functions are like the skeleton of a house, and stacking them up becomes the skeleton of a building. Have you ever seen an architect build the walls and pour cement himself? The same goes for writing code. Functions are stacked to form a skeleton. As for how to implement each function, please help me implement it (when you first learn, you are asked to help yourself implement it).

The above is the detailed content of Anonymous functions are a double-edged sword, with advantages and disadvantages. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

BTCC tutorial: How to bind and use MetaMask wallet on BTCC exchange? BTCC tutorial: How to bind and use MetaMask wallet on BTCC exchange? Apr 26, 2024 am 09:40 AM

MetaMask (also called Little Fox Wallet in Chinese) is a free and well-received encryption wallet software. Currently, BTCC supports binding to the MetaMask wallet. After binding, you can use the MetaMask wallet to quickly log in, store value, buy coins, etc., and you can also get 20 USDT trial bonus for the first time binding. In the BTCCMetaMask wallet tutorial, we will introduce in detail how to register and use MetaMask, and how to bind and use the Little Fox wallet in BTCC. What is MetaMask wallet? With over 30 million users, MetaMask Little Fox Wallet is one of the most popular cryptocurrency wallets today. It is free to use and can be installed on the network as an extension

Tips for dynamically creating new functions in golang functions Tips for dynamically creating new functions in golang functions Apr 25, 2024 pm 02:39 PM

Go language provides two dynamic function creation technologies: closure and reflection. closures allow access to variables within the closure scope, and reflection can create new functions using the FuncOf function. These technologies are useful in customizing HTTP routers, implementing highly customizable systems, and building pluggable components.

Considerations for parameter order in C++ function naming Considerations for parameter order in C++ function naming Apr 24, 2024 pm 04:21 PM

In C++ function naming, it is crucial to consider parameter order to improve readability, reduce errors, and facilitate refactoring. Common parameter order conventions include: action-object, object-action, semantic meaning, and standard library compliance. The optimal order depends on the purpose of the function, parameter types, potential confusion, and language conventions.

How to write efficient and maintainable functions in Java? How to write efficient and maintainable functions in Java? Apr 24, 2024 am 11:33 AM

The key to writing efficient and maintainable Java functions is: keep it simple. Use meaningful naming. Handle special situations. Use appropriate visibility.

Complete collection of excel function formulas Complete collection of excel function formulas May 07, 2024 pm 12:04 PM

1. The SUM function is used to sum the numbers in a column or a group of cells, for example: =SUM(A1:J10). 2. The AVERAGE function is used to calculate the average of the numbers in a column or a group of cells, for example: =AVERAGE(A1:A10). 3. COUNT function, used to count the number of numbers or text in a column or a group of cells, for example: =COUNT(A1:A10) 4. IF function, used to make logical judgments based on specified conditions and return the corresponding result.

Comparison of the advantages and disadvantages of C++ function default parameters and variable parameters Comparison of the advantages and disadvantages of C++ function default parameters and variable parameters Apr 21, 2024 am 10:21 AM

The advantages of default parameters in C++ functions include simplifying calls, enhancing readability, and avoiding errors. The disadvantages are limited flexibility and naming restrictions. Advantages of variadic parameters include unlimited flexibility and dynamic binding. Disadvantages include greater complexity, implicit type conversions, and difficulty in debugging.

What are the benefits of C++ functions returning reference types? What are the benefits of C++ functions returning reference types? Apr 20, 2024 pm 09:12 PM

The benefits of functions returning reference types in C++ include: Performance improvements: Passing by reference avoids object copying, thus saving memory and time. Direct modification: The caller can directly modify the returned reference object without reassigning it. Code simplicity: Passing by reference simplifies the code and requires no additional assignment operations.

What is the difference between custom PHP functions and predefined functions? What is the difference between custom PHP functions and predefined functions? Apr 22, 2024 pm 02:21 PM

The difference between custom PHP functions and predefined functions is: Scope: Custom functions are limited to the scope of their definition, while predefined functions are accessible throughout the script. How to define: Custom functions are defined using the function keyword, while predefined functions are defined by the PHP kernel. Parameter passing: Custom functions receive parameters, while predefined functions may not require parameters. Extensibility: Custom functions can be created as needed, while predefined functions are built-in and cannot be modified.

See all articles