箭头函数和普通函数的10个区别
1、箭头函数没有prototype属性
let fn = () => {};
fn.prototype === undefined; //true
2、箭头函数的this指向定义时外层第一个普通函数的this
let fn,
barObj = { message: 111 },
fooObj = { message: 222 };
function bar() {
// 运行时实例
fn();
}
function foo() {
// 定义时实例
fn = () => {
console.log('输出:', this); // 输出: {message: 222}
}
}
foo.call(fooObj);
bar.call(barObj);
3、不能直接修改箭头函数的this
let fn,
barObj = { message: 111 },
fooObj = { message: 222 };
function bar() {
// 运行时实例
fn.call({message: 333});
baz.call({message: 333})
}
function foo() {
// 定义时实例
fn = () => {
console.log('输出:', this); // 输出: {message: 222}
}
}
function baz() {
console.log('输出:', this); // 输出: {message: 333}
}
foo.call(fooObj);
bar.call(barObj);
// 这里如何能修改箭头函数this的指向了,我们可以间接操作。
// 修改箭头函数的this指向定义时外层第一个普通函数的this,来达到我们的目的
4、当箭头函数外层没有普通函数时,它的this在严格和非严格模式都是指向window。
5、箭头函数没有外层函数直接使用arguments会报错
let foo = () => {
console.log('输出:', arguments);
}
foo();
6、箭头函数有外层函数时,arguments继承自外层函数的arguments
function foo() {
console.log(arguments);
function boo () {
console.log(arguments);
function coo () {
console.log(arguments);
let aoo = () => {
console.log(arguments);
}
aoo('外层4');
}
coo('最外层3');
}
boo('外层2');
}
foo('外层1');
7、使用new调用箭头函数会报错
let aoo = () => {
console.log(arguments);
}
let boo = new aoo();
8、箭头函数没有外层函数时,new.target会报错
let a = () => {
console.log(new.target);
};
a();
9、箭头函数不支持重名参数
function foo(a, a) {
console.log(a, arguments);
}
var boo = (a, a) => {
console.log(a);
};
foo(1, 2);
boo(1, 2);
10、箭头函数语法更具优雅
- 箭头函数不用写function
- 箭头函数只有一个参数时,可以省略括号
- 箭头函数可以省略{}和return
总结
普通函数和箭头函数的区别:
- 箭头函数没有prototype(原型),所以箭头函数本身没有this
- 箭头函数的this在定义的时候继承自外层第一个普通函数的this。
- 如果箭头函数外层没有普通函数,严格模式和非严格模式下它的this都会指向window(全局对象)
- 箭头函数本身的this指向不能改变,但可以修改它要继承的对象的this。
- 箭头函数的this指向全局,使用arguments会报未声明的错误。
- 箭头函数的this指向普通函数时,它的argumens继承于该普通函数
- 使用new调用箭头函数会报错,因为箭头函数没有constructor
- 箭头函数不支持new.target
- 箭头函数不支持重命名函数参数,普通函数的函数参数支持重命名
- 箭头函数相对于普通函数语法更简洁优雅
注意事项:
- 箭头函数一条语句返回对象字面量,需要加括号
- 箭头函数在参数和箭头之间不能换行
- 箭头函数的解析顺序相对||靠前
不适用场景: 箭头函数的this意外指向和代码的可读性。