箭头函数
新增的定义函数的方式
const fn= ()=>{
console.log("hello world");
};
fn();
- 一般把箭头函数赋值给一个变量,通过变量名字调用函数
- 大括号里面仍然是函数体
特殊情况1:函数体中只有一句话 并且代码的执行结果就是返回值 ,可以省略大括号
//正常写法
function sum1(a,b){
return a+b;
}
const sum2= (a,b)=>a+b;
//创建一个变量result 接一下计算结果
let result=sum2(10,20);
console.log(result);
特殊情况2: 如果形参只有一个,可以省略小括号
function twice(a){
return a*2;
}
const twice2= a=>a*2;
let result=twice2(4);
console.log(result);
箭头函数的特点
1.没有prototype属性
function Star(uname, age,song) {
this.uname = uname;
this.age = age;
this.song=song;
}
console.log(Star.prototype);//Object
const fn= (a,b)=>{
return a+b;
};
console.log(fn.prototype);//undefined
2.箭头函数this为父作用域的this,不是调用时的this
普通函数this指向的是调用它的对象
箭头函数不绑定this ,箭头函数没有自己的this关键字,如果在箭头函数中使用this ,this指向箭头函数定义位置中的this
function fn(){
console.log(this);
return ()=>{
console.log(this);
}
}
const obj={name:'liu neng'};
// a相当于匿名函数的名字
const a=fn.call(obj);
a();
//输出两个相同的对象
// Object { name: "liu neng" }
// Object { name: "liu neng" }