this 指向
普通函数的 this 指向可以改变,箭头函数的 this 指向不能被改变,继承自上一级作用域中的 this。
var scope = 'window'
const obj = {
scope: 'obj',
logScope: () => {
console.log(this.scope)
},
logScopeNor: function() {
console.log(this.scope)
}
}
obj.logScope() // 'window'
obj.logScopeNor() // 'obj'
以上例子中,logScopeNor 方法是使用普通函数定义的,普通函数调用时,this 指向了当前的对象 obj,因此打印出的值是 ‘obj’。对象 obj 的 logScope 方法是用箭头函数定义的,指向了其定义时全局的作用域,因此打印出‘window’。
new
普通函数可以作为构造函数,箭头函数不能作为构造函数,使用 new 命令会抛出错误。
const bar = () => {
this.name = name;
};
const instance = new bar();
// Uncaught TypeError:
// bar is not a constructor
arguments 对象
箭头函数体内没有 arguments 对象,如果要用,需要使用 rest 参数代替。
// 打印 arguments
const bar = () => {
console.log(arguments);
};
bar(1, 2, 3);
// Uncaught ReferenceError:
// arguments is not defined
// 打印 rest 参数
const baz = (...args) => {
console.log("args", args);
};
baz(1, 2, 3);
// [1, 2, 3]
prototype
普通函数有原型对象 Function.prototype,箭头函数没有原型对象。
function foo() {}
console.log(foo.prototype)
// {constructor: ƒ}
const bar = () => {}
console.log(bar.prototype)
// undefined