箭头函数和普通函数的区别

定义

function fn(a, b) {
  return a+b;
}

var fn = (a, b) => {return a+b};

变量提升

由于 js 的内存机制,箭头函数需要先定义后调用

fn();  // 1
function fn() {
  console.log("1");
}
fn();  // Uncaught TypeError: fn is not a function
var fn = () => {
  console.log("1");
};

构造函数

箭头函数作为匿名函数,不能作为构造函数的,不能使用 new

function Student(name, age) {
  this.name = name;
  this.age = age;
}
var student = new Student("hello", 18);
var Student = (name, age) => {
  this.name = name;
  this.age = age;
};
var student = new Student("hello", 18); // Uncaught TypeError: Student is not a constructor

this 指向

使用 function 定义的函数,this 的指向随着调用环境的变化而变化的,而箭头函数中的 this 指向是固定不变的,一直指向的是定义函数的环境。因此,箭头函数不能使用 call() apply() bind() 等方法改变 this 的指向

function fn() {
  console.log(this);
}
var obj = {a: fn};
fn();  // window
obj.a();  // obj {a: fn}
var fn = () => {
  console.log(this);
};
var obj = {a: fn};
fn();  // window
obj.a();  // window

arguments

箭头函数不可以使用 arguments 对象,该对象在函数体内不存在。如果要用,可以使用 rest 参数代替

function fn() {
  console.log(arguments);
}
fn(); // Arguments [callee: ƒ, Symbol(Symbol.iterator): ƒ]
var fn = () => {
  console.log(arguments);
};
fn(); // Uncaught ReferenceError: arguments is not defined

你可能感兴趣的:(箭头函数和普通函数的区别)