箭头函数(Arrow Function)
ES6标准新增了一种新的函数:Arrow Function(箭头函数),使用箭头(=>)定义函数。
其特点是:1、如果形参只有一个,则小括号可以省略;2、函数体如果只有一条语句,则花括号可以省略,函数的返回值为该条语句的执行结果;3、箭头函数this指向声明时所在作用域下this的值;4、箭头函数不能作为构造函数实例化;5、不能使用arguments。
代码案例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>箭头函数,允许使用「箭头」(=>)定义函数</title>
</head>
<body>
<script>
// 0、使用箭头函数
let fn = (arg1,arg2,arg3) => {
return arg1 + arg2 + arg3;
}
console.log(fn("小桥","流水","人家"));
// 1、如果形参只有一个,则小括号可以省略
let fn2 = x => {return x+x};
console.log(fn2(2)); // 4
// 2、函数体如果只有一条语句,则花括号可以省略,函数的返回值为该条语句的执行结果
let fn3 = x => x+x;
console.log(fn3(3)); // 4
// 3、箭头函数this指向声明时所在作用域下this的值
function getId(){
console.log("getId",this.id);
return 41;
}
let getId2 = () =>{
console.log("getId2",this.id);
return 42;
}
//设置window对象的id属性
window.id = 9100;
// 直接调用
getId(); // getId 9100
getId2(); // getId2 9100
const user = {
id: 1314
}
// call 方法调用
getId.call(user); // getId 1314
getId2.call(user); // getId2 9100
// 4、箭头函数不能作为构造函数实例化
function Person(id,name){
this.id = id;
this.name = name;
}
let p1 = new Person(1,"辛巴");
console.log(p1);
// 箭头函数
let Person2 = (id,name)=>{
this.id = id;
this.name = name;
}
// Uncaught TypeError: Person2 is not a constructor
// let p2 = new Person2(1,"辛巴");
// 5、不能使用arguments
function getInfo(a,b,c){
console.log(arguments);
}
let getInfo2 = (a,b,c) =>{
// Uncaught ReferenceError: arguments is not defined
// console.log(arguments);
}
getInfo();
getInfo2();
// this指向声明时所在作用域中this的值
let learn = {
name: '小奋斗',
getName(){
let fn4 = () => {
console.log(this); // {name: '小奋斗', getName: ?}
}
fn4();
}
};
// 箭头函数不会更改this指向,用来指定回调函数会非常合适
learn.getName();
</script>
</body>
</html>