普通函数和箭头函数

2次阅读

共计 1010 个字符,预计需要花费 3 分钟才能阅读完成。

我常常的使用箭头函数,却还没有对箭头函数有个深入的了解,现在找一下这 2 个函数的不同点
1. 箭头函数本身没有 prototype(原型)
由于箭头函数没有原型,因此箭头函数本身没有 this
let a = () => {}
console.log(a.prototype) // undefined
let b = function () {}
console.log(b.prototype) // Object
2. 箭头函数的 this 指向在定义的时候继承自外层第一个普通函数的 this
let a;
let barObj = {
msg: ‘bar 的 this 指向 ’
}
let fooObj = {
msg: ‘foo 的 this 指向 ’
}
bar.call(barObj)
foo.call(fooObj) // {msg: ‘bar 的 this 指向 ’}
bar.call(fooObj)
a() // { msg: ‘foo 的 this 指向 ’}

function foo() {
a()
}
function bar () {
a = () => {
console.log(this)
}
}

从上面例子中可以得出 2 点:

箭头函数的 this 指向定义时所在的外层第一个普通函数,跟使用位置没有没有关系
被继承的普通函数的 this 指向改变,箭头函数的 this 也会跟着改变。
不能直接修改箭头函数的 this
可以通过修改被继承的普通函数的 this 指向,然后箭头函数的 this 也会跟着改变

3. 箭头函数使用 arguments
let b = () => {
console.log(arguments);
}
b(1,2,3,4) // arguments is not defined

function bar () {
console.log(arguments); // 完成第二个普通函数
bb(‘ 完成第一个普通函数 ’)
function bb() {
console.log(arguments); // 完成第一个普通函数
let a = () => {
console.log(arguments); // 完成第一个普通函数
}
a(‘ 箭头函数 ’)
}
}
bar(‘ 完成第二个普通函数 ’)
从上面可以得出以下 2 点

箭头函数指向 window 时,arguments 会报未定义的错误
如果不是 window, 那么就是外层第一个普通函数的 arguments

4. 箭头函数不可以使用 new
无论箭头函数的 this 指向哪里,使用 new 调用箭头函数都会报错,箭头函数没有构造函数
let a = () => {}
let b = new a() // a is not a constructor

正文完
 0