最近在学习ES6箭头函数,总结一下有几个特征
- 参数 => 表达式/语句
- 继承外层作用域
- 不能用作构造函数
- 没有prototype属性
下面针对这4点分别举例验证
1 基本格式 :
以前写法:
function foo (number){
return number * 5 ;
}
箭头函数写法
let foo = number => number*5 ;
let foo = number =>{
return number * 5 ;
}
2 继承外层作用域
let obj ={
commonFn:function(){
console.log(this)
},
arrowFn:()=>{
console.log(this)
}
}obj.commonFn(); // obj
obj.arrowFn(); // window
3 不能用作构造函数
用普通函数当作构造函数
let Fn = function(){
this.name = "common";
}
let fn = new Fn ();
console.log(fn.name)
用箭头函数当作构造函数(会报错)
let Fn = ()=>{
this.name = "common";
}
let fn = new Fn (); //报错: Fn is not a constructor
console.log(fn.name)
4 没有prototype属性
let commonFn = function(){}
let arrowFn = ()=>{}
console.log(commonFn.prototype); // {constructor: ƒ}
console.log(arrowFn.prototype); //undefined