ES6 中的箭头函数

来源:互联网 发布:mac用什么免费办公软件 编辑:程序博客网 时间:2024/05/16 08:42

定义

定义一个箭头函数很简单,基本语法是:

([param] [, param]) => {   statements}param => expression

param 是参数,根据参数个数不同,分这几种情况:

  • () => { ... } // 零个参数用 () 表示;
  • x => { ... } // 一个参数可以省略 ();
  • (x, y) => { ... } // 多参数不能省略 ();
当然,和普通函数一样,箭头函数也可以使用 ES6 新增的「默认参数」和「剩余参数」

var func1 = (x = 1, y = 2) => x + y;func1(); // 得到 3var func2 = (x, ...args) => { console.log(args) };func2(1,2,3); // 输出 [2, 3]

箭头函数允许多行语句或者单行表达式作为函数体。多行语句要用 {} 括起来;单行表达式不需要 {},并且会作为函数返回值:

x => { return x * x }; // 函数返回 x * xx => x * x; // 同上一行x => return x * x; // SyntaxError 报错,不能省略 {}x => { x * x }; // 合法,没有定义返回值,返回 undefined

JS 里的 this 指针一直是新手很头疼的事情,看一个简单的例子:

var o = {    x : 1,    func : function() { console.log(this.x) },    test : function() {        setTimeout(function() {            this.func();         }.bind(this), 100);    }};o.test();

本文链接:https://imququ.com/post/arrow-function-in-es6.html

0 0