微信公众号:路人zhang
扫码关注微信公众号

回复“面试手册”,获取本站PDF版

回复“简历”,获取高质量简历模板

回复“加群”,加入程序员交流群

回复“电子书”,获取程序员类电子书

当前位置: 前端 > javascript高频面试题 > 9.箭头函数和普通函数的区别
本文链接:https://www.mianshi.online/1382.html

(1)箭头函数语法更简洁

(2)箭头函数没有自己的this,需要通过查找作用域链来确定this的值,this 绑定的就是最近一层非箭头函数的 this。

var id = 1;
const fun = function () {
    setTimeout(() => {
    	console.log('id:', this.id);
    }, 100);
}
fun.call({ id: 2 }); // 箭头函数导致this总是指向函数定义生效时所在的对象,输出2

const fun1 = function () {
    setTimeout(function(){
    	console.log('id:', this.id);
    }, 100);
}
fun1.call({ id: 2 }); // 普通函数执行时,setTimeout中的this为window对象,输出1

(3)箭头函数没有自己的arguments对象,可以通过命名参数或者 rest 参数的形式访问参数

let fun = (...nums) => {
	console.log(nums)
}
let fun1 = function(){
	console.log(arguments)
}
fun(123) // 1,2,3
fun1(123) // Arguments对象

(4)不能通过 new 关键字调用

JavaScript函数有两个内部方法:[[Call]][[Construct]]

当通过new调用函数时,执行[Construct]]方法,创建一个实例对象,然后再执行函数体,将 this 绑定到实例上。当直接调用的时候,执行[[Call]]方法,直接执行函数体。箭头函数并没有[[Construct]]方法,不能被用作构造函数,如果通过 new 的方式调用,会报错。

var Fun = () => {};
var fun = new Fun(); // TypeError: Foo is not a constructor

(5) call()、apply()、bind()不能改变箭头函数中this的指向

var id = 'Global';
let fun = () => {
    console.log(this.id)
};
fun();                     // 'Global'
fun.call({id: 'Obj'});     // 'Global'
fun.apply({id: 'Obj'});    // 'Global'
fun.bind({id: 'Obj'})();   // 'Global'

(6)箭头函数没有原型:由于不能使用new调用箭头函数,所以也没有构建原型的需求,于是箭头函数也不存在prototype这个属性

(7)箭头函数不能用作Generator函数,不能使用yeild关键字

本站链接:https://www.mianshi.online如需勘误或投稿,请联系微信:lurenzhang888


点击面试手册,获取本站面试手册PDF完整版