代码改变世界

function 与 => 的区别

2017-08-18 20:31  阿诚de窝  阅读(17349)  评论(0编辑  收藏  举报

在JS中,箭头函数并不是简单的function(){}匿名函数的简写语法糖,实际上,箭头函数和匿名函数有个明显的区别:箭头函数内部的this是词法作用域,在编写函数时就已经确定了。而匿名函数的this指向运行时实际调用该方法的对象,无法在编写函数时确定。

我们看一下下面的例子:

 1 function Test() {
 2     this.num = 100;
 3 
 4     this.func = function(){
 5         console.log(this.num); // 100
 6         setTimeout(function(){
 7             console.log(this.num); // undefined
 8         }, 500);
 9     };
10 }
11 
12 var obj = new Test();
13 obj.func();

这里的方法里调用了setTimeout函数,该函数500毫秒后调用我们定义的函数时,实际上是window对象调用的,所以这时匿名函数的this是指向window而不是指向obj了。

在箭头函数出现之前一般都是这么写的:

 1 function Test() {
 2     this.num = 100;
 3 
 4     this.func = function(){
 5         console.log(this.num); // 100
 6         var that = this;
 7         setTimeout(function(){
 8             console.log(that.num); // 100
 9         }, 500);
10     };
11 }
12 
13 var obj = new Test();
14 obj.func();

这是利用了闭包的概念。箭头函数可以看做这种方式的语法糖。

如下:

 1 function Test() {
 2     this.num = 100;
 3 
 4     this.func = function(){
 5         console.log(this.num); // 100
 6         setTimeout(() => {
 7             console.log(this.num); // 100
 8         }, 500);
 9     };
10 }
11 
12 var obj = new Test();
13 obj.func();

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

  • 不可以当做构造函数,也就是说,不可以使用 new 命令,否则会抛出错误。
  • this、arguments、caller等对象在函数体内都不存在。
  • 不可以使用 yield 命令,因此箭头函数不能用作 Generator 函数。

总结

箭头函数除了传入的参数之外,其它的对象都没有!在箭头函数引用了this、arguments或者参数之外的变量,那它们一定不是箭头函数本身包含的,而是从父级作用域继承的。