Get the App
SLTechnology News&Howtos  ›  Development  › 

How JavaScript refines functions

Shulou Source: shulou.com Published: 2022-06-01 04:35:22 09月22日 Update

This article mainly introduces JavaScript how to refine the function, has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, the following let the editor take you to understand it.

Refinement function

Benefits:

Avoid oversized functions.

Independent functions help code reuse.

Independent functions are more likely to be overridden.

If a stand-alone function has a good name, it itself acts as an annotation.

Semantic implementation of multi-segment separate logic in different functions can make the code logic clear and clearly see what is being done at each step.

Code example:

The implementation acquires the data, then operates the dom to display the data, and finally adds events

Before function refinement

/ / the logic is written together. You need to read all the logic to know what this code is for. Local logic cannot reuse function main () {$.ajax.get ('/ getData'). Then ((res) = > {const ul = document.getElementById ('ul'); ul [XSS _ clean] = res.list.map (text = > `${text}`). Join ('\ n'); const list = document.getElementsByClassName ('li'); for (let I = 0; I)

< list.length; i ++) { list[i].addEventListener('focus', () =>

{/ / do something});});}

After function refinement

Function getData () {return $.ajax.get ('/ getData'). Then ((res) = > res.data.list);} function showList (list) {const ul = document.getElementById ('ul'); ul [XSS _ clean] = list.map (text = > `${text}`). Join ('\ n');} function addEvent () {const list = document.getElementsByClassName ('li'); for (let I = 0; I

< list.length; i ++) { list[i].addEventListener('focus', () =>

{/ / do something});}} / / the logic is clear, and some extracted functions can be reused async function main () {const list = await getData (); / get data showList (list); / / display page addEvent () / / add event} Thank you for reading this article carefully. I hope the article "how to extract the function of JavaScript" shared by the editor will be helpful to everyone. At the same time, I also hope that you will support and follow the industry information channel. More related knowledge is waiting for you to learn!

Tags: Functions logic code articles data reuse independence events differences clarity good value functions interests can make at the same time benefits local more friends Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Docker NVidia macOS Shulou Technology Huawei