箭头函数-迄今为止ES6最广泛使用的功能…
使用方法:除以下情况外,ES5的所有函数都应替换为ES6的箭头函数:
不应该使用箭头函数:
When we want function hoisting
as arrow functions are anonymous.
When we want to use this/arguments in a function
as arrow functions do not have this/arguments of their own, they depend upon their outer context.
When we want to use named function
as arrow functions are anonymous.
When we want to use function as a constructor
as arrow functions do not have their own this.
When we want to add function as a property in object literal and use object in it
as we can not access this (which should be object itself).
让我们来了解箭头函数的一些变体,以便更好地理解:
变体1:当我们想要向一个函数传递多个参数并从中返回某个值时。
ES5版本:
var multiply = function (a, b) {
return a*b;
};
console.log(multiply(5, 6)); // 30
ES6版本:
var multiplyArrow = (a, b) => a*b;
console.log(multiplyArrow(5, 6)); // 30
注意:
function关键字不是必需的。
=>是必需的。
{}是可选的,当我们不提供{}return是由JavaScript隐式添加的,当我们提供{}时,如果我们需要它,我们需要添加return。
变体2:当我们只想将一个参数传递给一个函数并从它返回某个值时。
ES5版本:
var double = function(a) {
return a*2;
};
console.log(double(2)); // 4
ES6版本:
var doubleArrow = a => a*2;
console.log(doubleArrow(2)); // 4
注意:
当只传递一个参数时,我们可以省略括号,()。
变体3:当我们不想向函数传递任何参数,也不想返回任何值时。
ES5版本:
var sayHello = function() {
console.log("Hello");
};
sayHello(); // Hello
ES6版本:
var sayHelloArrow = () => {console.log("sayHelloArrow");}
sayHelloArrow(); // sayHelloArrow
变体4:当我们想显式地从箭头函数返回时。
ES6版本:
var increment = x => {
return x + 1;
};
console.log(increment(1)); // 2
变体5:当我们想从箭头函数返回一个对象时。
ES6版本:
var returnObject = () => ({a:5});
console.log(returnObject());
注意:
我们需要用括号()将对象括起来。否则,JavaScript无法区分块和对象。
变体6:箭头函数没有自己的参数(类似object的数组)。它们依赖于参数的外部上下文。
ES6版本:
function foo() {
var abc = i => arguments[0];
console.log(abc(1));
};
foo(2); // 2
注意:
foo是一个ES5函数,它有一个类似object的参数数组,传递给它的参数是2,所以foo的参数[0]是2。
abc是一个ES6的箭头函数,因为它没有自己的参数。因此,它输出foo的参数[0],而不是它的外部上下文。
变体7:箭头函数本身没有这个,它们依赖于外部上下文
ES5版本:
var obj5 = {
greet: "Hi, Welcome ",
greetUser : function(user) {
setTimeout(function(){
console.log(this.greet + ": " + user); // "this" here is undefined.
});
}
};
obj5.greetUser("Katty"); //undefined: Katty
注意:
传递给setTimeout的回调是一个ES5函数,它有自己的this,在严格使用的环境中没有定义。因此,我们得到输出:
undefined: Katty
ES6版本:
var obj6 = {
greet: "Hi, Welcome ",
greetUser : function(user) {
setTimeout(() => console.log(this.greet + ": " + user));
// This here refers to outer context
}
};
obj6.greetUser("Katty"); // Hi, Welcome: Katty
注意:
传递给setTimeout的回调是一个ES6箭头函数,它没有自己的this,所以它从它的外部上下文greetUser中获取它,greetUser有this。它是obj6,因此我们得到输出:
Hi, Welcome: Katty
杂项:
我们不能对箭头函数使用new。
箭头函数没有原型属性。
当通过apply或call调用箭头函数时,我们没有这个绑定。