工作中经常使用箭头函数,但是一直不清楚箭头函数和普通函数的具体区别,下边就梳理一下。
箭头函数的特点
- 箭头函数语法格式,因为是匿名函数,只能使用函数表达式
// 箭头函数只能使用函数表达式
let fn = () => {}
// 普通函数可以使用函数表达式和函数声明
let fn = function() {} // 函数表达式
function fn() {} // 函数声明
- 箭头函数是匿名函数,没有new 和 prototype。不能作为构造函数
// 定义匿名函数
let fn = () => {console.inf(1)}
// 执行
fn() // 1
// 打印匿名函数
console.info(fn) // () => {console.inf(1)}
// 打印匿名函数的原型属性
console.info(fn.__proto__) // ƒ () { [native code] }
// 打印匿名函数的原型对象
console.info(fn.prototype) // undefined
// 作为构造函数new实例,抛异常
try {
let fn2 = new fn()
console.info(fn2)
} catch(err) {
console.info(err) // fn is not a constructor
}
- 箭头函数没有arguments
// 普通函数
let fn3 = function() {
console.info(arguments, arguments.length)
}
// 执行
fn3() // Arguments[], 0
// 箭头函数
let fn4 = () => console.info(arguments)
// 执行抛异常
fn4() // arguments is not defined
4.this一般指向全局window,如果被普通函数包含指向上一层函数的对象
var age = 20
let obj = {
age: 30,
fn5: function() {
setTimeout(function() {
console.info(this, this.age, 5)
}, 100)
}
}
obj.fn5() // window, 20, 5
let obj2 = {
age: 40,
fn6: function() {
setTimeout(() => {
console.info(this, this.age, 6)
}, 100)
}
}
obj2.fn6() // obj2{}, 40, 6
5.可以使用call、apply、bind方法,但不可以修改this指向
let age = 20
let obj = {
age: 30
}
// 普通函数
let fn = function() {
console.info(this.age)
}
// 执行
fn() // 20
fn.call(obj) // 30
// 箭头函数
let fn4 = () => console.info(this.age)
// 执行
fn4() // 20
fn4.call(obj) // 20
箭头函数的实现原理
1.实现原理待研究