-
箭头函数的形态
let fn = function(a,b) { return a+b } //省去了function 在参数后面加了 => let fn = (a,b) => { return a + b; }
-
箭头函数的特点
-
this是静态的
function getName1(){ console.log(this.name); } let getName2 = () => { console.log(this.name); } window.name = "window" const li = { name:"lili" }; // //直接调用 getName1(); //window getName2(); //window // //call 方法调用(call可以改变this的指向,让其指向()内对象) getName1.call(li); //lili getName2.call(li); //window
this是静态的,this始终指向函数声明时所在作用域下
- 不能用于构造实例化对象
//传统方式 let Person1 = function (name,age) { this.name = name this.age = age } function hhh(name,age){ this.name = name this.age = age } let zhangsan1 = new Person1("张三","13") console.log(zhangsan1.name) //张三 //箭头函数 let Person = (name,age) =>{ this.name = name this.age = age } let zhangsan = new Person("张三","13") //报错,可知箭头函数不能用于构造实例化对象 console.log(zhangsan.name)
-
不能使用arguments
let fn1 = function(){ console.log(arguments) } fn1(1,2,3) //输出结果 // Arguments(3) [1, 2, 3, callee: ƒ, Symbol(Symbol.iterator): ƒ] // 0: 1 // 1: 2 // 2: 3 // callee: ƒ () // length: 3 // Symbol(Symbol.iterator): ƒ values() // __proto__: Object let fn = () =>{ console.log(arguments) } fn(1,2,3) //输出结果 //arguments is not defined
-
箭头函数的简写
// 当参数只有一个时,可以省略小括号 // 当代码体只有一行语句时,直接写该代码, //且return必须省略,返回值就是语句的执行结果 let pow = n =>n*n console.log(pow(3))
箭头函数适合与 this 无关的回调. 定时器, 数组的方法回调,箭头函数不适合与 this 有关的回调. 事件回调, 对象的方法。
- 若使用了箭头函数还想正常使用 this ,一般我们会将this进行保存,方便使用。
- 不适用于事件回调用,比如下面的addEventListener,后面的function,指向div,如果此处使用箭头函数,就指向外部了。
// 点击 div 2s 后颜色变成『粉色』 //箭头函数 var div = document.getElementById("id") div.onclick = function(){ setTimeout(() => { console.log(this) //div this.style.background = "pink" }, 1000) } //function定义的函数 div.addEventListener("click",function(){ let _this = this;//保存 setTimeout(function(){ //console.log(this) //window //this.style.background = "pink" //报错 _this.style.background = "pink"//将保存值进行使用 }) })
- 但是对于定时器来说,直接使用function定义,其中this指向window,但是如果是用箭头函数,this指向函数声明时所在作用域。
- 除此对象的方法也是如此,如果方法写的是箭头函数,那么该方法就指向了该对象的外部。