js function articles-personal understanding of lazy functions

The idea of ​​lazy functions is somewhat similar to the following scenario:

Imagine Zhang San typing in abc

General functions:

function 打字(内容){
    
    
	console.log("看文稿")
	console.log("输入",内容)
}
打字("a")		//看文稿 	输入a 
打字("b")		//看文稿 	输入b
打字("c")		//看文稿 	输入c

Lazy function:

function 打字(内容){
    
    
  console.log("看文稿")
  打字 = function(内容){
    
    
		console.log("輸入",内容)
  }
  return 打字(内容)
}
打字("a")	//看文稿 	输入a 
打字("b")	//       	输入b 
打字("c")	//		 	输入c 

The above can be the difference between a simple ordinary function and a lazy function: the
function will go through all the method bodies each time it is executed, but sometimes a certain piece of logic does not need to be executed every time. Here we need the addition of lazy functions.

When the function is executed for the first time, all method bodies will be walked once. After the public part is completed, the method will be reassigned in the method body, the local function will be reassigned to the function body itself, and the function body will be returned. Then the second and subsequent method calls will not go to the public part (after all, the method body has been changed, if this is still going, this is not a corpse)

General function Lazy function
Zhang San read the manuscript Zhang San read the manuscript
Zhang San input a Zhang San input a
Zhang San read the manuscript Zhang San input b
Zhang San input b Zhang San input c
Zhang San read the manuscript
Zhang San input c

Normal function is to type one word
per word, but for lazy function, you don’t need to read it after reading the manuscript once and type directly.

Lazy functions can be further rewritten:

let 打字 = (function (){
    
    
  console.log("看文稿")
  return function (内容){
    
    
    console.log("輸入",内容)
  }
})()
打字("a")	//看文稿 	输入a 
打字("b")	//       	输入b 
打字("c")	//		 	输入c 

If there is a more beautiful writing, welcome to discuss, let us make continuous progress in an orderly manner.
If you like it, you might as well click a small like and follow. Your like and follow will be my continuous driving force.

Guess you like

Origin blog.csdn.net/qq_33226029/article/details/109226750