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


js箭头函数和普通函数的区别

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 '=>'


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM