当前位置:网站首页>New feature in ES6 -- arrow function

New feature in ES6 -- arrow function

2022-06-11 09:38:00 Snatch bamboo shoots 123

Define format

var  Function name =( Function parameter )=> Function return value ;

Examples of arrow function usage

// No function arguments 
var fun=()=>5;
// amount to 
var fun=function(){
    
	return 5
}

// Single function parameter 
var pow1 = num => Math.pow(num,2);
var pow1=function(num){
    
	return Math.pow(num,2);
}

// Multiple function arguments 
var sum = (num1, num2) => num1 + num2;  // amount to var sum = (num1, num2) => {return num1+num2};
var sum=function(num1,num2){
    
	return num1+num2;
}

effect

  1. Simplify callback functions
//sort Callback function in function 
var result = array.sort((a, b) => a - b);
// amount to 
var result = array.sort(function (a, b) {
    
  return a - b;
});

Callback function : Is passed as an argument to another parameter and is called in the function , Functions used to complete certain tasks

  1. Simplify the expression
// Define a tool function to calculate the square value of a number 
const pow_1=num=>num**2
pow_1(n)

characteristic

(1) Arrow function does not have its own this object .

(2) Can't be used as a constructor , in other words , You cannot use... For arrow functions new command

(3) Not available arguments object , The object does not exist inside the function .

(4) Not available yield command

Be careful

When the return value of the function is an object , You need to put brackets

var myobj= name => ({
    name: "Temp" ,age: 19});

Use example of arrow function

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title> This is a html5 demo</title>
</head>
<body>
    <script> var num1=1,num2=2 var sum = (num1, num2) => {
      return num1+num2}; // var sum = (num1, num2) => num1+num2 var pow_1=num=>num**2 var fun=()=>5; console.log(fun()) console.log(pow_1(num2)) console.log(sum(num1,num2)) </script>
</body>
</html>

Chrome Browser run results
 Insert picture description here

原网站

版权声明
本文为[Snatch bamboo shoots 123]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/162/202206110914078073.html