箭头函数与普通函数的区别

普通函数与箭头函数的区别

1、不邦定this

在箭头函数出现之前,每个新定义的函数都有其自己的 this

var myObject = {
  value:1,
  getValue:function(){
    console.log(this.value)
  },
  double:function(){
    return function(){
      console.log(this.value = this.value * 2); 
    }
  }
}

myObject.double()();  //希望value乘以2
myObject.getValue();  //1

在ECMAscript5中将this赋给一个变量来解决:

var myObject = {
  value:1,
  getValue:function(){
    console.log(this.value)
  },
  double:function(){
    var that = this;
    return function(){
      console.log(that.value = that.value * 2); 
    }
  }
}

myObject.double()();  //2
myObject.getValue();  //2

除此之外,还可以使用 bind 函数,把期望的 this 值传递给 double() 函数。

var myObject = {
  value:1,
  getValue:function(){
    console.log(this.value)
  },
  double:function(){
    return function(){
      console.log(this.value = this.value * 2); 
    }.bind(this)
  }
}

myObject.double()();  //2
myObject.getValue();  //2

箭头函数会捕获其所在上下文的 this 值,作为自己的 this 值,因此下面的代码将如期运行。

var myObject = {
  value:1,
  getValue:function(){
    console.log(this.value)
  },
  double:function(){
    //回调里面的 `this` 变量就指向了期望的那个对象了
    return ()=>{
      console.log(this.value = this.value * 2); 
    }
  }
}

myObject.double()();  
myObject.getValue();  

2、使用call()和apply()调用

由于 this 已经在词法层面完成了绑定,通过 call() 或 apply() 方法调用一个函数时,只是传入了参数而已,对 this 并没有什么影响:

 var myObject = {
  value:1,
  add:function(a){
    var f = (v) => v + this.value;
    return f(a);
  },
  addThruCall:function(a){
    var f = (v) => v + this.value;
    var b = {value:2};
    return f.call(b,a);
    
  }
}

console.log(myObject.add(1));    //2
console.log(myObject.addThruCall(1));    //2

3、箭头函数不绑定arguments,取而代之用rest参数…解决

var foo = (...args) => {
  return args[0]
}

console.log(foo(1))    //1

4、使用new操作符

箭头函数不能用作构造器,和 new 一起用就会抛出错误。

var Foo = () => {};
var foo = new Foo();  //Foo is not a constructor		

5、使用原型属性

箭头函数没有原型属性。

var foo = () => {};
console.log(foo.prototype) //undefined

6、不能简单返回对象字面量

var func = () => {  foo: 1  };
// Calling func() returns undefined!
var func = () => {  foo: function() {}  };
// SyntaxError: function statement requires a name
//如果要返回对象字面量,用括号包裹字面量
var func = () => ({ foo: 1 });

7、箭头函数当方法使用的时候没有定义this绑定

var obj = {
  value:1,
  add:() => console.log(this.value),
  double:function(){
    console.log(this.value * 2)
  }
}

obj.add();  //undefined
obj.double(); //2

8、箭头函数不能换行

var func = ()
           => 1; // SyntaxError: expected expression, got '=>'
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值