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

用例参考 http://es6.ruanyifeng.com/#docs/function#箭头函数

先看一个实例

 var sum = (num1, num2) => num1 + num2;
    //等价于
 var sum = function (num1, num2) {
        return num1 + num2;
    }

关于this

通函数中的this指向函数被调用的对象,因此对于不同的调用者,this的值是不同的

箭头函数没有它自己的this值,箭头函数内的this值继承自外围作用域
正是因为它没有this,所以也就不能用作构造函数
不可以当作构造函数,也就是说,不可以使用new命令,否则会抛出错误

var fun=(a,b)=>a+b;
var fun1=new fun(1,2);
  console.log(fun1);
//报错
"error"
"TypeError: fun is not a constructor
    at <anonymous>:3:13
    at https://static.jsbin.com/js/prod/runner-4.0.4.min.js:1:13850
    at https://static.jsbin.com/js/prod/runner-4.0.4.min.js:1:10792"

箭头函数体内的this对象,就是 定义时所在的对象,而不是使用时所在的对象。而普通函数中this指向是可变的,普通函数的this指向调用它的那个对象

window.color = "red";
//let 声明的全局变量不具有全局属性,即不能用window.访问
function foo() {
  setTimeout(() => {
    console.log('id:', this.id);
  }, 100);
}

var id = 21;

foo.call({ id: 42 });
// id: 42

setTimeout的参数是一个箭头函数,这个箭头函数的定义生效是在foo函数生成时,而它的真正执行要等到100毫秒后。如果是普通函数,执行时this应该指向全局对象window,这时应该输出21。但是,箭头函数导致this总是指向函数定义生效时所在的对象(本例是{id: 42}),所以输出的是42

所以箭头函数无法使用call()或apply()来改变其运行的作用域。

window.color = "red";
let color = "green";
let obj = {
  color: "yellow"
};
let sayColor = () => {
  return this.color;
};
sayColor.apply(obj);//red

关于arguments

  • 箭头函数不可以使用arguments对象,该对象在函数体内不存在。如果要用,可以用 rest 参数代替

关于yield

  • 不可以使用yield命令,因此箭头函数不能用作 Generator 函数

箭头函数没有原型属性

var a = ()=>{
  return 1;
}

function b(){
  return 2;
}

console.log(a.prototype);//undefined
console.log(b.prototype);//object{...}

猜你喜欢

转载自blog.csdn.net/weixin_34015566/article/details/86918438
今日推荐