箭头函数
前言
注意:箭头函数与普通函数区别可不止this指向不同这一个知识点哦~。
箭头函数的不同点
- 语法更简洁、直观。
- 从作用域上层继承
this
。 bind、call和apply
对箭头函数没效果。- 不绑定
arguments
对象。 - 不能使用
new
关键字。 - 没有原型
(prototype)
。
1.语法更简洁
(param1, param2, …, paramN) => { return statements }
(param1, param2, …, paramN) => statements
// 只有一个参数的时候圆括号是可选的
(param1) => statements
// 如果返回的statements是对象的话,需要圆括号括起来
param1 => (statements)
// 没有参数时是一对圆括号
() => { statements }
复制代码
2.从作用域上层继承this。
// 通过bable将ES6转化为ES5
// ES6
const obj = {
getArrow() {
return () => {
console.log(this === obj);
};
}
}
// 转化后ES5
var obj = {
getArrow: function getArrow() {
var _this = this;
return function () {
console.log(_this === obj);
};
}
};
复制代码
从转化后的代码可知箭头函数this为定义时获取,并不是在调用时获取到this。
3.bind、call和apply对箭头函数没效果
从转化后的箭头函数代码可知,在执行函数中并没有"this",而是直接拿到的变量,所以对箭头函数使用call、apply和bind也是没有效果的。
4.不绑定arguments
对象。
箭头函数没有自己的arguments
对象
// 第一种
let f = (v) => {
console.log(v)
console.log(arguments)
}
f(123) // 报错: arguments is not defined
// 第二种
let f = function (v) {
console.log(arguments) // [123]
return () => {
// 继承上层作用域的arguments
console.log(arguments) // [123]
}
}
f(123)() // 不报错
复制代码
如果上层作用域是全局就会报错,否则是继承上层作用域的arguments
。
5. 不能使用new关键字
箭头函数不能用作构造器,和 new
一起用会抛出错误。
var Foo = () => {};
var foo = new Foo(); // TypeError: Foo is not a constructor
复制代码
6. 没有原型(prototype)
箭头函数没有prototype
属性。
var Foo = () => {};
console.log(Foo.prototype); // undefined
复制代码
在回顾一遍:
- 箭头函数语法更简洁,
- 箭头函数的this是继承的上层作用域。
- 箭头函数没有属于自己的argumnets。
- 箭头函数使用call、bind、apply是不会更改this指向的,就是简单的传递参数。
- 箭头函数不能使用new关键字。
- 箭头函数没有prototype属性。
看到这里你没有疑问吗???,为什么不能使用new关键字呢
因为new
这个关键字底层使用了prototype、argumnets 和call来处理,箭头函数里没有argumnets和prototype,然后call对箭头函数没有效果。自然new就不好使了,都是连锁反应.....。
参考文献:
MDN 箭头函数