ES6新特性之箭头函数与function的区别

发布时间:2019-08-10 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了ES6新特性之箭头函数与function的区别脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

1.写法不同

// function的写法
function fn(a, b){
    return a+b;
}
// 箭头函数的写法
let foo = (a, b) =>{ return a + b }

2.this的指向不同

function中,this指向的是调用该函数的对象;

//使用function定义的函数
function foo(){
    console.LOG(this);
}
VAR obj = { aa: foo };
foo(); //Window
obj.aa() //obj { aa: foo }

而在箭头函数中,this永远指向定义函数的环境。

//使用箭头函数定义函数
var foo = () => { console.log(this) };
var obj = { aa:foo };
foo(); //Window
obj.aa(); //Window
function Timer() {
  this.s1 = 0;
  this.s2 = 0;
  // 箭头函数
  setInterval(() => {
     this.s1++;
     console.log(this);
  }, 1000); // 这里的this指向timer
  // 普通函数
  setInterval(function () {
    console.log(this);
    this.s2++; // 这里的this指向window的this
  }, 1000);
}

var timer = new Timer();

setTimeout(() => console.log('s1: ', timer.s1), 3100);
setTimeout(() => console.log('s2: ', timer.s2), 3100);
// s1: 3
// s2: 0

3.箭头函数不可以当构造函数

//使用function方法定义构造函数
function PErson(name, age){
    this.name = name;
    this.age = age;
}
var lenhart =  new Person(lenhart, 25);
console.log(lenhart); //{name: 'lenhart', age: 25}
//尝试使用箭头函数
var Person = (name, age) =>{
    this.name = name;
    this.age = age;
};
var lenhart = new Person('lenhart', 25); //Uncaught TypeError: Person is not a constructor

另外,由于箭头函数没有自己的this,所以当然也就不能用call()、apply()、bind()这些方法去改变this的指向。

4.变量提升

function存在变量提升,可以定义在调用语句后;

foo(); //123
function foo(){
    console.log('123');
}

箭头函数以字面量形式赋值,是不存在变量提升的;

arrowFn(); //Uncaught TypeError: arrowFn is not a function
var arrowFn = () => {
    console.log('456');
};
console.log(F1); //function f1() {}   
console.log(f2); //undefined  
function f1() {}
var f2 = function() {}

脚本宝典总结

以上是脚本宝典为你收集整理的ES6新特性之箭头函数与function的区别全部内容,希望文章能够帮你解决ES6新特性之箭头函数与function的区别所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。