Different forms of JavaScript functions, function is an expression, function is a value, the difference between function declaration and line number expression

different forms of functions

A function can be an expression

In "JavaScript Functions" above, we introduced that a JavaScriptfunction is a syntactic construct that encapsulates a block of code for reusing code.

as follows:

function add(a,b){
    
    
	return a + b;
}

The above code declares a function for summation as a function definitionadd , and we can reuse this code by the function name .

In fact, we have another way to define a function, which is to treat the function as an expression , or a function expression , and assign the expression to a variable.

as follows:

let add = function(a,b){
    
    
	return a+b;
};//这里有分号

//以下这种方式可能更容易理解
let add = function(a,b){
    
     return a+b; };

The above code is an assignment statement. The left side is a variable letdefined with a keyword add, and the right side is a function expression. The meaning of the statement is to assign the function expression on the right side to the variable on the left side add.

Attention: Note that there is no function name in the function expression on the right. It is allowed to omit the name of the function in the function expression. We call this function definition without a name an anonymous function .

The function definition method of the latter expression type is the same as the previous function declaration function. In short, it is to define a function and store it in a addvariable .

When using a function expression, the semicolon needs to be added at the end of the statement ;. This semicolon is part of the assignment statement, not the syntax requirement of the function definition.

The essence of a function is a value

The above code reflects two different ways of defining a function, but no matter which method is used, it cannot change the essence of a function as a value.

The above two definition methods both use a addvariable named to store a function, and we can also print the value of the variable:

function add1(a,b){
    
    
	return a+b;
}
let add2 = function(a,b){
    
     return a+b; };

console.log(add1);
console.log(add2);

The print result is as follows:

This proves that in JavaScript, a function is a special value, and if we print this value, we get the function's source string.

It should be noted that no matter which method is used to define the function, if the function name is used directly, for example add1, the add2function will not be executed, and the calling function needs to be added ().

Since a function is a value, we can perform some variable operations on it, such as assignment, copying, etc.

Take a small plum:

function add(a,b){
    
    	//定义了一个函数变量add
	return a+b;
}
let otherAdd = add;	//变量复制

console.log(add(1,1));
console.log(otherAdd(1,2));

Code execution result:

What happens to the above code:

  1. First use the function declaration, create a function, and put the function into a variable add;
  2. Copy the value in the function variable add(that is, the function) to another variable otherAdd. Note that there is addnothing behind here (). If you bring ()it , you will assign add()the function execution result to the otherAddvariable;
  3. Finally , the same function is stored internally, and when it is called as a function, it will have the same effect, that is, to realize the addition of numbers add.otherAdd

Of course, the code is written the following way to have the same effect:

let add =function(a,b){
    
     return a+b; };
let otherAdd = add;

console.log(add(1,1));
console.log(otherAdd(1,2));

A string or number represents the value of "data", and a function can be understood as the value of "behavior"; the
same thing is that they can be passed as the value of a variable;
the difference is that the "data" value is used for calculation, For comparison, the "behavior" value is available for "execution".

Callback

As mentioned above, the essence of a function is a special value. Since it is a value, it can be passed as a parameter!

Functions passed as parameters are often called callback functions .

Take a chestnut:

function ask(ques, yes,no){
    
    
	if(confirm(ques)){
    
    
		yes();
	}else{
    
    
		no();
	}
}

function selectedYes(){
    
    
	console.log('安排');
}

function selectedNo(){
    
    
	console.log('下次一定');
}

// 将selectedYes和selectedNo作为参数传入ask函数
ask('点个关注,干不干?',selectedYes,selectedNo);

The above code is very common in the actual development process, and the two functions askpassed in the function are called callback functions (callbacks).selectedYesselectedNo

In simple terms, we pass a function as a parameter and expect this function to be executed ("callback") at some point in the future.
For example, in the above example selectedYesis Yesthe callback for selectedNothe answer, the callback for the answer No.

In addition to the writing in the above example, we can also pass the callback function directly in the form of an anonymous function , thus greatly shortening the code:

function ask(ques,yes,no){
    
    
	if(confirm(ques)){
    
    
		yes();
	}else{
    
    
		no();
	}
}

ask(
	'点个关注?',
	function(){
    
    console.log('好说');},
	function(){
    
    console.log('想得美');}
);//调用

The above way of passing anonymous functions directly in the function call process is a JavaScriptvery obvious feature, and it is also a very important feature. We will see this feature appearing all the time in various projects~~~

The way the anonymous function is passed into the callback can make the callback JavaScriptalmost completely anonymous, and can only askbe accessed inside the function, which is exactly the result we want~~

Difference between function expression and function declaration

  • grammatical differences

A function declaration creates a separate function in the code file:

function add(a,b){
    
    
	return a+b;
}

Function expressions create functions within an expression or within another syntactic construct:

let add = function(a,b){
    
    
	return a+b;
}
  • When does the engine create the function

Function expressions are created after the code is executed to the expression, and can only be used from the creation

When the code is executed to let func = function(){...}the right, the function is created, which is available when the function is assigned to a variable func.

Function declarations are defined before all code is executed, and you can use

This is because, JavaScriptwhen the engine executes the script, it first finds all global functions from the entire file, and then creates these functions.

As a result of this feature, we can use functions before function declarations:

add(1,2);	//函数还没有创建的时候就可以使用了

function add(a,b){
    
     //在程序执行之初就被创建
	return a+b;
}

The code execution result is as follows:

If the function is declared as an expression, an error will be reported:

add(1,2);//报错
let add = function(a,b){
    
     return a+b; }
  • scope

In strict mode, function declarations are only {...}visible inside the code block ( ) in which they are declared, and cannot be used outside the code, just like local variables.

for example:

let score = prompt('请输入你的期末成绩',0);

//在if语句中声明一个函数
if(score > 80){
    
    
	function doSomething(){
    
    
		console.log('好学生')//输出好好学生
	}
}else{
    
    
	function doSomething(){
    
    
		console.log('找个厂吧')//建议打工
	}
}

doSomething();//报错,函数不存在

In theory, score > 80the will define a function to output "good student", and in other cases, output "find a factory", and then ifcall it later.

However, due to the nature of the function declaration, it can only be ifseen inside the code block of the statement, and cannot be used outside, so the code will report an error.

How to deal with it? Here you can use function expressions, which is also the difference between the two:

let score = prompt('请输入你的期末成绩',0);

let doSomething;
if(score>80){
    
    
	doSomething = function(){
    
    
		console.log('好学生');
	}
}else{
    
    
	doSomething = function(){
    
    
		console.log('找个厂吧');
	}
}

doSomething();

after class homework

Using the ternary operator, rewrite the following code:

let score = prompt('请输入你的期末成绩',0);

let doSomething;
if(score>80){
    
    
	doSomething = function(){
    
    
		console.log('好学生');
	}
}else{
    
    
	doSomething = function(){
    
    
		console.log('找个厂吧');
	}
}

doSomething();

Guess you like

Origin blog.csdn.net/weixin_43302112/article/details/124460279