ES6箭头函数

一、语法

根据参数个数不同,分这几种情况: 
    1、() => { … } // 零个参数用 () 表示; 
    2、x => { … } // 一个参数可以省略 (); 
    3、(x, y) => { … } // 多参数不能省略 ();

1、 具有一个参数的简单函数

var single = a => a
single('hello, world') // 'hello, world'

2、没有参数的需要用在箭头前加上小括号

var log = () => {
    alert('no param')
}

3、多个参数需要用到小括号,参数间逗号间隔,例如两个数字相加

var add = (a, b) => a + b
add(3, 8) // 11

4、函数体多条语句需要用到大括号

var add = (a, b) => {
    if (typeof a == 'number' && typeof b == 'number') {
        return a + b
    } else {
        return 0
    }
}

5、. 返回对象时需要用小括号包起来,因为大括号被占用解释为代码块了

var getHash = arr => {
    // ...
    return ({
        name: 'Jack',
        age: 33
    })
}

6、直接作为事件handler

document.addEventListener('click', ev => {
    console.log(ev)
})

7、作为数组排序回调

var arr = [1, 9 , 2, 4, 3, 8].sort((a, b) => {
    if (a - b > 0 ) {
        return 1
    } else {
        return -1
    }
})
arr // [1, 2, 3, 4, 8, 9]

二、注意点
1. typeof运算符和普通的function一样

var func = a => a
console.log(typeof func); // "function"

2、instanceof也返回true,表明也是Function的实例

console.log(func instanceof Function); // true

3、this固定,不再善变

obj = {
    data: ['John Backus', 'John Hopcroft'],
    init: function() {
        document.onclick = ev => {
            alert(this.data) // ['John Backus', 'John Hopcroft']
        }
        // 非箭头函数
        // document.onclick = function(ev) {
        //     alert(this.data) // undefined
        // }
    }
}
obj.init()

这个很有用,再不用写me,self,_this了,或者bind。

5、不能使用argument

var func = () => {
    console.log(arguments)
}
func(55) //

三、特性
箭头函数内部没有constructor方法,也没有prototype,所以不支持new操作。但是它对this的处理与一般的普通函数不一样。箭头函数的 this 始终指向函数定义时的 this,而非执行时。我们通过一个例子来理解:

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

o.test(); // TypeError : this.func is not a function

上面的代码会出现错误,因为this的指向从o变为了全局(函数调用中的this都是指向全局的)。如果大家对JavaScript中的this不是很熟悉的话,可以看看我写过的一篇文章,深入理解javascript之this。好了,回归正题,我们需要修改上面的代码如下:

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

o.test();

通过使用外部事先保存的this就行了。这里就可以利用到箭头函数了,我们刚才说过,箭头函数的 this 始终指向函数定义时的 this,而非执行时。所以我们将上面的代码修改如下:

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

o.test();

这回this就指向o了。

我们还需要注意一点的就是这个this是不会改变指向对象的,我们知道call和apply可以改变this的指向,但是在箭头函数中是无效的。

var x = 1,
    o = {
        x : 10,
        test : () => this.x
    };

o.test(); // 1
o.test.call(o); // 依然是1

四、代码示例:
看看在ES5中的函数怎么通过ES6中的箭头函数来替代吧:

// ES5
var selected = allJobs.filter(function (job) {
  return job.isSelected();
});

// ES6
var selected = allJobs.filter(job => job.isSelected());

当然,也可以定义多个参数:

// ES5
var total = values.reduce(function (a, b) {
  return a + b;
}, 0);

// ES6
var total = values.reduce((a, b) => a + b, 0);

当然=>后面也不一定非得接return 之后的语句,看下面:

// ES5
$("#confetti-btn").click(function (event) {
  playTrumpet();
  fireConfettiCannon();
});
// ES6
$("#confetti-btn").click(event => {
  playTrumpet();
  fireConfettiCannon();
});

但是需要注意的是,多行语句需要用{}括起来,单行表达式不需要{},并且会作为函数返回值。

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

和普通函数一样,箭头函数也可以使用剩余参数和默认参数。

var func1 = (x = 1, y = 2) => x + y;
func1(); // 得到 3

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

原文链接:
http://www.cnblogs.com/snandy/p/4403111.html
http://blog.csdn.net/mevicky/article/details/49942559

相关: http://kangax.github.io/compat-table/es6/

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值