JavaScript箭头函数
目录
在本教程中,您将借助示例学习JavaScript箭头函数 。
箭头功能是JavaScript的ES6版本中引入的函数之一。与常规函数相比,它可以使您以更简洁的方式创建函数。例如,
这个函数
// function expression let x = function(x, y) { return x * y; }
可以写成
// using arrow functions let x = (x, y) => x * y;
使用箭头函数。
箭头功能语法
箭头函数的语法为:
let myFunction = (arg1, arg2, ...argN) => { statement(s) }
这里,
-
myFunction
是函数的名称 -
arg1, arg2, ...argN
是函数参数 -
statement(s)
是函数主体
如果主体具有单个语句或表达式,则可以将箭头函数编写为:
let myFunction = (arg1, arg2, ...argN) => expression
示例1:无参数的箭头功能
如果函数不带任何参数,则应使用空括号。例如,
let greet = () => console.log('Hello'); greet(); // Hello
示例2:具有一个参数的箭头函数
如果一个函数只有一个参数,则可以省略括号。例如,
let greet = x => console.log(x); greet('Hello'); // Hello
示例3:箭头函数作为表达式
您还可以动态创建一个函数并将其用作表达式。例如,
let age = 5; let welcome = (age < 18) ? () => console.log('Baby') : () => console.log('Adult'); welcome(); // Baby
示例4:多行箭头功能
如果函数主体具有多个语句,则需要将它们放在大括号{}
。例如,
let sum = (a, b) => { let result = a + b; return result; } let result1 = sum(5,7); console.log(result1); // 12
带有箭头功能
在常规函数, 此关键字引用调用它的函数 。
但是, this
与箭头功能无关。 Arrow 函数没有自己的this
。因此,无论何时调用this
,它都指向其父范围。例如,
在常规函数
function Person() { this.name = 'Jack', this.age = 25, this.sayName = function () { // this is accessible console.log(this.age); function innerFunc() { // this refers to the global object console.log(this.age); console.log(this); } innerFunc(); } } let x = new Person(); x.sayName();
输出
25 undefined Window {}
在这里, this.age
this.sayName()
内的this.sayName()
是可访问的,因为this.sayName()
是对象的方法。
但是, innerFunc()
是常规函数 , this.age
无法访问this.age
因为this
引用了全局对象(浏览器中的Window对象)。因此, this.age
innerFunc()
函数内部的innerFunc()
给出了undefined
。
内箭函数
function Person() { this.name = 'Jack', this.age = 25, this.sayName = function () { console.log(this.age); let innerFunc = () => { console.log(this.age); } innerFunc(); } } let x = new Person(); x.sayName();
输出
25 25
在这里, innerFunc()
函数是使用arrow 函数定义的。在arrow 函数内部, this
是指父级的范围。因此, this.age
给出25 。
参数绑定
常规函数具有参数绑定。这就是为什么在将参数传递给常规函数时可以使用arguments
关键字访问它们的原因。例如,
let x = function () { console.log(arguments); } x(4,6,7); // Arguments [4, 6, 7]
箭头函数没有参数绑定。
当您尝试使用arrow 函数访问参数时,它将给出错误。例如,
let x = () => { console.log(arguments); } x(4,6,7); // ReferenceError: Can't find variable: arguments
要解决此问题,可以使用传播语法。例如,
let x = (...n) => { console.log(n); } x(4,6,7); // [4, 6, 7]
带承诺和回调的箭头功能
箭头函数提供了更好的语法来编写promise和回调。例如,
// ES5 asyncFunction().then(function() { return asyncFunction1(); }).then(function() { return asyncFunction2(); }).then(function() { finish; });
可以写成
// ES6 asyncFunction() .then(() => asyncFunction1()) .then(() => asyncFunction2()) .then(() => finish);
箭头功能应避免的事情
1.不应使用箭头功能在对象内部创建方法。
let person = { name: 'Jack', age: 25, sayName: () => { // this refers to the global ..... // console.log(this.age); } } person.sayName(); // undefined
2.您不能将arrow 函数用作构造函数 。例如,
let Foo = () => {}; let foo = new Foo(); // TypeError: Foo is not a constructor
注意 :箭头功能在ES6中引入。某些浏览器可能不支持使用箭头功能。访问JavaScript Arrow Function支持以了解更多信息。
总计 0 评论