es6——箭头函数

基本用法

  • es6新增了箭头函数,举个例子
  • 基本语法
let func = value => value;

相当于

let func = function(value){
	return value;
}
  • 如果需要给函数传入多个参数或不需要参数,使用一个圆括号将参数部分括起来:
let func = (value, num) => value * num;
  • 如果箭头函数的代码块部分多于一条语句或箭头函数直接返回一个对象,就要使用大括号将它们括起来,并且使用return语句返回:
let func = (value, num) => {
    return value * num
};

let func = (value, num) => ({total: value * num});

  • 与变量解构结合
let func = ({value, num}) => ({total: value * num})

// 使用
var result = func({
    value: 10,
    num: 10
})

console.log(result); // {total: 100}

箭头函数与普通函数的区别

  1. 没有this
    箭头函数没有 this,所以需要通过查找作用域链来确定 this 的值。
    即,箭头函数被非箭头函数包含,this 绑定的就是最近一层非箭头函数的 this。
    举个例子:点击button变色
function Button(id) {
    this.element = document.querySelector("#" + id);
    this.bindEvent();
}

Button.prototype.bindEvent = function() {
    this.element.addEventListener("click", this.setBgColor, false);
};

Button.prototype.setBgColor = function() {
    this.element.style.backgroundColor = '#1abc9c'
};

var button = new Button("button");

这样的写法是不对的,因为当使用 addEventListener() 为一个元素注册事件的时候,事件函数里的 this 值是该元素的引用。setBgColor 中 this 指向 button 元素,this.element 为undefined。
也许你想这么改

Button.prototype.setBgColor = function() {
    this.style.backgroundColor = '#1abc9c'
};

但是这在开发里是不规范的,我们希望 setBgColor 中的 this 是指向实例对象的,这样就可以调用其他的函数。

解决方案

  • 利用es5和click, bind 强制绑定 setBgColor() 的 this 为实例对象
Button.prototype.bindEvent = function() {
    this.element.addEventListener("click", this.setBgColor.bind(this), false);
};
  • 使用es6
Button.prototype.bindEvent = function() {
    this.element.addEventListener("click", event => this.setBgColor(event), false);
};

前面说了,箭头函数没有 this,所以会向外层查找 this 的值。在本例中向上找this,即 bindEvent 中的 this,此时 this 指向实例对象,所以可以正确的调用 this.setBgColor 方法。
如果我们将bindEvent 和 setBgColor改成箭头函数,会导致函数里的 this 指向 window 对象 (非严格模式下)。

  1. 没有 arguments
    箭头函数没有自己的arguments对象,但箭头函数可以访问外围函数的 arguments 对象:
function constant() {
    return () => arguments[0]
}

var result = constant(2);
console.log(result()); // 2

当然我们可以通过命名参数或者 rest 参数的形式访问箭头函数自己的参数:

let nums = (...nums) => nums;
  1. 不能通过 new 关键字调用
    JavaScript 函数有两个内部方法:[[Call]] 和 [[Construct]]。
    当通过 new 调用函数时,执行 [[Construct]] 方法,创建一个实例对象,然后再执行函数体,将 this 绑定到实例上。
    当直接调用的时候,执行 [[Call]] 方法,直接执行函数体。
    箭头函数并没有 [[Construct]] 方法,不能被用作构造函数,如果通过 new 的方式调用,会报错。

嵌套箭头函数

let insert = (value) => ({into: (array) => ({after: (afterValue) => {
  array.splice(array.indexOf(afterValue) + 1, 0, value);
  return array;
}})});

insert(2).into([1, 3]).after(1); //[1, 2, 3]

管道机制:前一个输出是后一个的输入

const plus1 = a => a + 1;
const mult2 = a => a * 2;

mult2(plus1(5))
// 12
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值