一、语法
箭头函数使用紧凑的语法,没有自己的this,arguments,super,new.target绑定。箭头函数不能作为构造函数使用且使用箭头函数时不能使用arguments对象
//普通函数
function sum(a, b) {
return a + b;
}
//箭头函数
const sum = (a, b) => a + b;
二、this指向
普通函数中的this指向动态变化,this的值由函数的调用方式决定。箭头函数中的this指向是在定义的时候就被确定的,也就是它所处的词法作用域中的this值。
//普通函数
const obj = {
x: 1,
getX() {
return this.x;
}
}
console.log(obj.getX()) // 1
const getX = obj.getX;
console.log(getX()) // undefined
//箭头函数
const obj = {
x: 1,
getX: () => {
return this.x;
}
}
console.log(obj.getX()) // undefined
三、绑定
普通函数可以使用call()、apply()、bind()方法将this指向绑定到指定对象,但箭头函数不可以。箭头函数中的this是无法被改变的。
//普通函数
const obj1 = { value: 1 };
const obj2 = { value: 2 };
function getValue(name) {
console.log(name + this.value);
}
getValue.call(obj1, 'obj1'); // 输出:obj11
getValue.call(obj2, 'obj2'); // 输出:obj22
//箭头函数
const obj1 = { value: 1 };
const obj2 = { value: 2 };
const getValue = (name) => {
console.log(name + this.value);
}
getValue.call(obj1, 'obj1'); // 输出:obj2undefined
getValue.call(obj2, 'obj2'); // 输出:obj2undefined
四、使用场景
箭头函数相对于普通函数来说更适用于短小的回调函数,使用箭头函数可以让代码更加简洁易懂。
//普通函数
[1, 2, 3].map(function (x) {
return x * x;
});
//箭头函数
[1, 2, 3].map((x) => x * x);
五、作用域
箭头函数中没有单独的函数作用域,它与定义时外层的作用域共享。普通函数中,有自己的作用域。
//普通函数
var x = 'global';
function foo() {
var x = 'function';
return function () {
console.log(x);
}
}
var bar1 = foo();
bar1(); //function
//箭头函数
var x = 'global';
function foo() {
var x = 'function';
return () => console.log(x);
}
var bar2 = foo();
bar2(); //function
原创文章,作者:QEGWI,如若转载,请注明出处:https://www.506064.com/n/349452.html
微信扫一扫
支付宝扫一扫