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

How to master JS high-level programming skills

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

Share

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

This article mainly explains "how to master JS high-level programming skills". The content of the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "how to master JS high-level programming skills".

Singleton design pattern

Use a separate instance to manage the relevant characteristics of the current thing, generally referring to attributes and methods, similar to the characteristics of implementing grouping, binding all the feature descriptions of an instance into a group.

Take a look at a simple singleton design pattern:

Let module1 = (function () {function tools () {} function share () {} return {name: 'house', tools};}) (); module1.tools ()

Here we can expose the methods defined by the module1 module for use by external modules.

There is also a singleton pattern based on closure implementation called the advanced singleton design pattern, which was the most commonly used modular idea for team collaboration before vue/react came out, and is often used to divide modules.

The singleton pattern in the form of closures is as follows:

Let A = (function () {function fn () {B.getXxx ();} function query () {} return {query}) (); let B = (function () {function fn () {} function getXxx () {} A.query (); return {getXxx}}) ()

In the above example, we can define two modules An and B, first declare the function in our own module, and then expose it to each other's module to use, this is the earliest modular idea, but also the advanced singleton design pattern.

Inert function

Let's start with an example that encapsulates a function that gets the style of an element.

To get the style, we usually think of the two API, window.getComputedStyle and element.currentStyle, but their execution is also conditional.

For example, the former is only compatible with Google browsers, while the latter is compatible with IE browsers.

Function getCss (element, attr) {if ('getComputedStyle' in window) {return window.getComputedStyle (element) [attr];} return element.currentStyle [attr];} getCss (document.body,' margin'); getCss (document.body, 'padding'); getCss (document.body,' width')

From this example, we can see that if you need to get the style of the element three times, it is obvious that each time you enter the function, you need to determine whether the method is compatible or not, which results in unnecessary waste. The best solution-the idea of inert function.

Generally speaking, the lazy function initializes the execution of the first rendering, and if the second execution is the same, we need to solve this problem with the idea of closure.

Function getCss (element, attr) {if ('getComputedStyle' in window) {getCss = function (element, attr) {return window.getComputedStyle (element) [attr];};} else {getCss = function (element, attr) {return element.currentStyle [attr];};} / to get the value return getCss (element, attr);} getCss (document.body,' margin') for the first time GetCss (document.body, 'padding'); getCss (document.body,' width')

In this function, when we execute the getCss function for the first time, we can already determine whether getComputedStyle is compatible or not, so there is no need to judge the second time, according to the results returned by the first judgment, directly determine which API is used for the second and third function execution, so that each function execution will be less than a layer of judgment, which improves the running speed of js to a certain extent.

So let's see, where is this inertia reflected?

Process: in fact, it is the first time that the getCss function creates a private execution context in the global scope, and the getCss function is regenerated in it, and its reference address is re-assigned to the global function getCss, resulting in that the global getCss cannot be released, forming a closure. Each time it is executed later, the small function getCss is executed.

Kohllized function

The meaning of the function is to pass parameters to the function step by step, pass some parameters each time, and return a more specific function to receive the remaining parameters, which can be nested with multiple layers of functions that receive partial parameters until the final result is returned.

The most basic Corey split

/ / original function function add (a, b, c) {return a + b + c;} / / Corialized function function addCurrying (a) {return function (b) {return function (c) {return a + b + c;} / / call original function add (1, 2, 3); / / 6 / / call Corialized function addCurrying (1) (2) (3) / / 6

The return value of the function addCurrying is a function each time, and the next parameter is used as the formal parameter. Until all three parameters are passed in, the summation operation is performed inside the last function returned, which actually makes full use of the characteristics of the closure.

General purpose type of packaging

The above Coriarization function does not involve high-order functions, nor is it universal, so it is impossible to convert functions with arbitrary or unknown number of formal parameters.

Let's encapsulate a general-purpose Corey conversion function, which can convert any function into Corey.

/ / the parameters of add are not fixed Look at the cumulative addition of several numbers: function add (arecine bdhocrect d) {return a+b+c+d} function currying (fn,... args) {/ / the summation of the parameters of the fn.length callback function / / the summation of the parameters after the args.length currying function / / such as: add (arecine bdhorem d) currying (add,1,2) 3 if (fn.length = args.length) {return fn (... args)} else {/ / continue to pass parameters newArgs step by step parameters return function anonymous (... newArgs) {/ / combine the parameters passed first and the parameters passed later let allArgs = [... args,... newArgs] return currying (fn) ... allArgs)}} let fn1 = currying (add, 1,2) / / 3 let fn2 = fn1 (3) / / 6 let fn3 = fn2 (4) / / 10

Kohli's function thought

Using the closure preservation mechanism, some information is stored in advance (the idea of preprocessing)

We describe it with a question of summation:

Function currying (... outerArgs) {return function anonymous (... innerArgs) {let args = outerArgs.concat (innerArgs) return args.reduce ((previousValue, currentValue) = > previousValue + currentValue)}} let fn1 = currying (1,2) let fn2 = fn1 (3) let fn3 = fn2 (4)

Supplement the idea of what is preconditioning:

When the fn1 function is executed for the first time, a function execution context is created and 1,2 is stored in the local variable in that context. When you execute fn2 fn3 later, you need to get the return result of fn1 first. Using the stored 1,2 parameters, this mechanism forms a closure.

Friends who don't understand reduce look at this:

When case 1:reduce does not have a second parameter

Let Array = [10, 20, 30, 40, 50]; Array.reduce (previousValue, currentValue, currentIndex, arr) {return previousValue + currentValue;}

When the function is triggered for the first time, previousValue is the first term (10) and currentValue is the second term (20)

When the function is triggered the second time, previousValue is the return value of the callback function (30), and currentValue is the third term (30).

When the function is triggered for the X time, previousValue is the return value of the callback function, and currentValue is the item X + 1.

CurrentIndex: corresponds to the index value of currentValue

Arr: it's a constant array itself.

When the case 2:reduce has a second parameter

Let Array = [10,20,30,40,50]; Array.reduce ((previousValue, currentValue, currentIndex, arr) {return previousValue + currentValue;}, 0)

When the function is triggered for the first time, previousValue is the second parameter (0) and currentValue is the first term (10)

When the function is triggered the second time, previousValue is the return value of the callback function (10), and currentValue is the second term (20).

When the function is triggered for the X time, previousValue is the return value of the callback function, and currentValue is the item X.

CurrentIndex: corresponds to the index value of currentValue

Arr: it's a constant array itself.

Compose function

Compose composite function: flattening the nested calls of multi-tier functions

Compose functions often solve the problem of flattening function calls based on the idea of reduce-based functions:

In the project, we often encounter such a problem:

Const fn1 = x = > x + 10; const fn2 = x = > x-10; const fn3 = x = > x * 10; const fn4 = x = > x / 10; console.log (fn1 (fn2 (fn1 (4))

In the above example, it is obvious that the hierarchical nesting is deep, so it is necessary to call the idea of function flattening.

Function call flattening: if it is a multi-level nested function, call one function and pass it to the next function as an argument to another function

Solution: execute from left to right

/ * * @ param funcs Storage functions executed in sequence (array) = > [fn1, fn3, fn2, fn4] * @ param args stores the argument information that the first function execution needs to pass (array) = > [5] * / function compose (... funcs) {return function anonymous (... args) {if (funcs.length = 0) return args; if (funcs.length = 1) return funcs [0] (... args) / / when there are multiple functions in funcs, return funcs.reduce ((n, func) = > {/ / first execution: / / n: the argument func of the first function execution: the value of the first function / / second execution: / / n: the return value after the last func execution Pass as an argument to the next function to execute func: the second function, return Array.isArray (n)? Func (... n): func (n);}, args)}} let res = compose (fn1, fn3, fn2, fn4) (5) / / execution process: console.log (compose () (5)); / / = > 5 console.log (compose (fn1) (5)); / / > 5 console.log 10 = 15 console.log (compose (fn1, fn3) (5)); / / > fn1 (5) = 15 fn3 (15) = 150 console.log (compose (fn1, fn3, fn2) (5)) / / = > fn1 (5) = 15 fn3 (15) = 150 fn2 (150) = 140 console.log (compose (fn1, fn3, fn2, fn4) (5)); / / = > fn1 (5) = 15 fn3 (15) = 150 fn2 (15) = 140 fn4 (140) = 14

The execution process of flattening the compose function:

Hongmeng official Strategic Cooperation to build HarmonyOS Technology Community

Compose () (5). If no function argument is passed in the compose () function, the following argument 5 will be returned directly.

Compose (fn1, fn3, fn2, fn4) (5), first execute fn1 (5), and then pass the result of fn1 (5) to fn3, such as fn3 (fn1 (5)) = > fn3 (15), and so on fn2 (fn3 (fn1 (5)) = > fn4 (150). Later, the parameters of each function call are the results returned by the previous function, so naturally we think of the Array.prototype.reduce method.

The second parameter of reduce is set to unify n as the return result of each function (the first n is 5 fn1), and it just needs to be executed by the fn1 (5) function. It can be seen that the necessity of the second parameter is to unify that the return result of each callback function is number.

Functional programming and imperative programming

Callback function: pass one function as a value to another function and execute the function in another function (this is an important knowledge for implementing functional programming)

Functional programming: pay attention to the results, do not care about the process, the process to others to deal with, reflecting the idea of function encapsulation (advocated)

Imperative programming: pay attention to the process and need to implement the process on your own.

Functional programming: how to encapsulate the logic into an API method. We only need to call the API method to get the desired results.

Let arr = [10,20,30,40,50]; let res = arr.reduce ((n, item) = > {return n + item;})

Imperative programming: implement the main logic in code and pay attention to the process

Let res = 0; for (let I = 0; I < arr.length; iTunes +) {res + = arr [I];} Thank you for reading, the above is the content of "how to master JS high-level programming skills". After the study of this article, I believe you have a deeper understanding of how to master JS high-level programming skills, 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