箭头函数:
函数名=(参数)=>{返回值})
- 函数有参数:
1个参数
let f=v=>v;
console.log(f(1));//1
// 等价于
let fun=function(v){
return v;
}
多个参数
// 多个参数
let more=(a,b)=>a+b;
console.log(more(3, 4));//7
// 等价于
let more=function(a,b){
return a+b;
}
console.log(more(3, 4));//7
- 不带参数的函数:
//不带参数
let ff=()=>1;
// 等价于
let ff=function(){
return 1;
}
console.log(ff());//1
- 既不带参数也不带返回值
let fff=()=>{
console.log(1);
}
fff();//1
- 返回值是数组:
let f=()=>[1,2,3];
console.log(f());//(3) [1, 2, 3]
返回值是对象:要在返回值外加括号
let f=()=>({a:1,b:2});
console.log(f());//{a: 1, b: 2}
箭头函数与解构赋值结合使用
let f=({a,b})=>{
console.log(a, b);
}
f({a:1,b:2});//1 2
重点:箭头函数this
指针保持前后一致
Ps:
map的参数为:value,index,值在前,索引在后
let arr=[9,8,7,6,5];
arr.map((val,index)=>{
console.log(val, index);
console.log(this);//window
})
例如settimeout
计时器this
指针的修改
{
function person(){
this.getsex=()=>{
console.log(this);
setTimeout(()=>{
//在修改为箭头函数后this指针和上面一致,指向person而不是window
console.log(this);
},1);
}
}
let p=new person();//new之后修改了this指针为person
p.getsex();
}
练习1:
和上面的案例很像,上面的案例是在
new
对象的时候修改了this
指针,而次案例使用了call
替换this
指针
{
function foo() {
console.log(this);//{id:1}
setTimeout(() => {
console.log(this.id);//保持上下文一致,输出1
}, 100);
}
var id = 21;
foo.call({id:1});//用当前对象替换foo里的this指针
}
练习2:
输出为2是因为第一个
return
函数没有使用箭头函数,所以不会和上文一致变为id:1
function foo() {
console.log(this)//id:1
return function (){
console.log(this)//id:2
return () => {
return () => {
console.log('id:', this.id);//2
};
};
}
}
var id=100;
var f = foo.call({id: 1});//替换最外层函数的指针为{id: 1}
var t1 = f.call({id: 2})()(); // 替换第一个return函数下的指针为{id: 2}
练习3:
输出为1是因为第一个
return
使用箭头函数,所以和上文一致变为id:1
function foo() {
console.log(this)//id:1
return ()=>{
console.log(this)//id:1
return () => {
return () => {
console.log('id:', this.id);//1
};
};
}
}
var id=100;
var f = foo.call({id: 1});//替换最外层函数的指针为{id: 1}
var t1 = f.call({id: 2})()(); // 替换第一个return函数下的指针为{id: 2}
箭头函数不适用 的两个场景:
在对象里面的函数(方法内包含this
)
调用
cat.jumps()
时,如果是普通函数,该方法内部的this
指向cat
;如果写成上面那样的箭头函数,使得this指向全局对象,因此不会得到预期结果。
const cat = {
lives: 9,
jumps: () => {
console.log(this);//window
this.lives--;
}
}
cat.jumps();
正常使用时
const cat = {
lives: 9,
jumps: function() {
console.log(this);//{lives: 9, jumps: ƒ}
this.lives--;
}
}
cat.jumps();
dom对象的事件(需要动态的this时)
正常情况
var button = document.getElementsByClassName('press')[0];
button.addEventListener('click', function() {
console.log(this);//<button class="press on">按钮</button>
this.classList.toggle('on');
});
修改后由于this指针改变,浏览器报错Cannot read property 'toggle' of undefined
var button = document.getElementsByClassName('press')[0];
button.addEventListener('click', ()=> {
console.log(this);//window
this.classList.toggle('on');
});
箭头函数的嵌套
改写1:
/* function Data(){
return {
getInfo:function (){
return "你好";
}
}
}*/
let f=()=>({getinfo:()=>"这是一个改写测试"});
console.log(f().getinfo());//这是一个改写测试