箭头函数区别总结:
- this永远指向上下文,call,apply,bind无法改变。
- 不能作为构造函数,使用new命令
- 箭头函数不绑定arguments,取而代之用rest参数…
- 箭头函数没有原型属性prototype // undefined
- 箭头函数不能当做Generator函数,不能使用yield关键字
- 变量提升
- 箭头函数不能换行
- 右侧直接为表达式时,直接return
箭头函数区别详解:
- 箭头函数this永远指向上下文this,call,apply,bind都无法改变this指向
通过 call() 或 apply() 方法调用一个函数时,只是传入了参数而已,对 this并没有什么影响
var obj = {
a: 10,
b: function(n){
var f = (v) => v + this.a;
return f(n);
},
c: function(n) {
var f = (v) => v + this.a;
var m = {a:20};
return f.call(m,n);
}
}
console.log(obj.b(1)); //11
console.log(obj.c(1)); //11
- 不能作为构造函数,不能使用new
var B = ()=>{
value:1;
}
var b = new B(); //TypeError: B is not a constructor
- 箭头函数不绑定arguments,取而代之用rest参数…
function A(a){
console.log(arguments); //[object Arguments] {0: 1}
}
var B = (b)=>{
console.log(arguments); //ReferenceError: arguments is not defined
}
var C = (...c)=>{ //...c即为rest参数
console.log(c); //[3]
}
A(1);
B(2);
C(3);
- 箭头函数没有原型属性
var a = ()=>{
return 1;
}
function b(){
return 2;
}
console.log(a.prototype);//undefined
console.log(b.prototype);//object{...}
-
箭头函数不能当做Generator函数,不能使用yield关键字
-
变量提升
由于js的内存机制,function的级别最高,而用箭头函数定义函数的时候,需要var(let、const)关键字,而var所定义的变量不能得到变量提升。故箭头函数一定要定义于调用之前。
- 箭头函数不能换行
var a = ()
=>1; //SyntaxError: Unexpected token =>
网友评论