There are two ways to define a function in JavaScript and to assign a function variable

  • 2020-03-30 02:55:00
  • OfStack

 
<!DOCTYPE html> 
<html> 
<head> 
<meta charset="UTF-8"> 
<title>Insert title here</title> 
<script type="text/javascript"> 
 
//= = = = = = = = = = = = = = = = = = js function in the two types of definition and function of variable assignment = = = = = = = = = = = = = = = =
//Defining a function in javascript can be interpreted as defining a variable
//Variables in js are weakly typed.
//----------1 
//function add1(){ 
//alert("add1"); 
//} 
//So the function as a variable, as an argument, is add1, which points to the first address that the block stores in memory
var add1=new Function("alert('add1');");//--------2 
//The above 1,2 notation is completely equivalent, which is the two ways of declaring functions in js
//In fact, it's add1 that points to the first address of this block of code stored in memory.
//As for how to store, heap or stack, I won't do much research here.

var addtt=add1;//Function names can be assigned or passed as variables
//Addtt points to the body of the function
addtt(); 
//= = = = = = = = = = = = = = = = = = js function in the two types of definition and function of variable assignment = = = = = = = = = = = = = = = =
//= = = = = = = = = = = = = = = = = = the function variables passed as a parameter = = = = = = = = = = = = = = = = = = = = = = = = = = =
//Basic format:
function add2(fun){ 
//Pass the function name as an argument
fun(); 
} 
add2(add1); 

//-------------------------------------- 
//This is demonstrated by using a function as an argument and accepting arguments at the same time
function add(a){ 
return n+10; 
} 
//A: Numbers. Fun: functions
function addTest(a,fun){ 
var t=fun(a); 
return t; 
} 
var tt=addTest(22,add);//That's also ok
alert(tt); 
//= = = = = = = = = = = = = = = = = = the function variables passed as a parameter = = = = = = = = = = = = = = = = = = = = = = = = = = =
</script> 
</head> 
<body> 

</body> 
</html> 

Related articles: