1. 箭头函数
const add = function(x, y) { return x + y; };
const add = (x, y) => x + y;
const greet = () => "Hello, World!";
2. 箭头函数没有arguments
const fn = function () {
console.log(arguments);
console.log(arguments instanceof Array);
}
fn()
const fn2 = (...arg) => {
console.log(arg);
console.log(arg instanceof Array);
console.log(arguments);
}
fn2()
3. 箭头函数没有自己的this
- 箭头函数的
this 值是在创建函数时继承自外部作用域,而不是在运行时确定。
const fn = function () {
console.log(this);
}
fn()
const fn2 = () => {
console.log(this);
}
fn2()
const obj={
hello:()=>{
console.log(this);
}
}
obj.hello()
const obj2 = {
hello: function () {
const test = () => {
console.log(this);
}
test()
}
}
obj2.hello()
const test3 = obj2.hello
test3()
4. 箭头函数中的this无法通过call()、apply、bind()修改
5. 箭头函数无法作为构造函数使用
6. 优先使用箭头函数