ES6箭头函数与function区别是什么?

发布时间:2020-04-15 14:05:47 作者:小新
来源:亿速云 阅读:534

今天小编给大家分享的是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区别是什么就分享到这里了,当然并不止以上和大家分析的办法,不过小编可以保证其准确性是绝对没问题的。希望以上内容可以对大家有一定的参考价值,可以学以致用。如果喜欢本篇文章,不妨把它分享出去让更多的人看到。

推荐阅读:
  1. ES6如何使用箭头函数
  2. 普通函数与箭头函数在JavaScript中的区别是什么

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

javascript 箭头函数 别是

上一篇:CDN选型前的测试方法

下一篇:html中article标签的作用是什么?

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》