一、定义
箭头函数使用 => 定义函数,参数和箭头之间不能换行,没有return将返回代码块的结果
const fn = () => 1;
//等同于
function fn() {
return 1;
}
参数只有一个时可以不用加括号
const fn = a => a;
大括号会被解释为代码块,所以返回值为对象时,应该加上一对括号
const fn = () => ({ name: "zhangsan", age: 18 });
console.log(fn()); // {name: 'zhangsan', age: 18}
二、区别
没有自己的this,箭头函数的this为父作用域的this,定义时就已经确认并且不能更改,不能用call()、apply()、bind()方法去改变this的指向。
const obj = {
fn: () => {
console.log(this); // Window {window: Window, self: Window, document: document, name: '', location: Location, …}
},
a: function a() {
const fn1 = () => {
console.log(this); // {fn: ƒ, a: ƒ}
};
fn1();
},
};
obj.fn();
obj.a();
没有arguments和prototype
const a = 1;
const fn = (a) => {
console.log(arguments);
};
fn(a); // ReferenceError: arguments is not defined
console.log(fn.prototype); //undefined
不能作为构造函数使用new命令。
const fn = () => {
console.log(1);
};
let f = new fn(); //TypeError: fn is not a constructor