再不用ES6就Out了--函数的新特性

本文介绍了ES6中函数默认值、rest参数及扩展运算符的应用,并对比了箭头函数与传统函数的区别,展示了箭头函数如何绑定this。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

函数默认值

默认值这要是针对参数传入为undefined的值。ES6之前的写法:

  function add(x, y) {
    x = x || 1;
    y = y || 1;
    return x + y;
  }
  console.log(add()); // 2

进入ES6的你:

function add(x = 1, y = x) {
  return x + y;
}
console.log(add()); // 2

这里有一点要注意的:(函数内不能再重新声明参数变量)

function add(x = 1, y = 1) {
  let x = 20; //Error
  const y = 20; //Error
}

rest参数

说到rest参数,首先介绍一下新的运算符,扩展运算符(…)
* 将一个数组变为参数数列。

  let arr = [1,2,3];
  console.log(Object.prototype.toString.call(...arr)); //[object Number]这点有点奇怪
  console.log(...arr); //1 2 3

怎么用扩展运算符来成就rest参数呢:

  function add(...numbers) {
    let sum = 0;
    for (let val of numbers) {
      sum += val;
    }
    return sum;
  }
  let arr = [1,2,3,4,5];
  console.log(add(1,2,3,4,5)); //15
  console.log(add(...arr)); //15
  //ES5的写法
  console.log(add.apply(null,arr)); //15

注意事项:
* rest参数只能是最后一个参数(剩下的参数的意思)
* 使用rest参数代替arguments

箭头函数

ES6之前的写法:

  function add(x, y) {
    return x + y;
  }

进入ES6你可以采用这样的姿势:

  单个参数 单条语句
  let add = n => n * 10;

  多个参数,多条语句
  let add = (x = 1, y = x) => {
    x = x * 10;
    y = y - 10;
    return x * y;
  }

是不是简洁明了。接下来让我们来看一段代码更深入的了解箭头函数:

  ES6之前:
  function old() {
    function temp() {
      console.log('==========old============');
      console.log(this); // window
      console.log(this.name) //global
    }
    temp();
  }
  var name = 'global';
  old.call({name: 'xiaoming'});

  ES6:
  let newFunc = function () {
    let temp = () => {
      console.log("=========new===========");
      console.log(this); //Object {name: "xiaoming"}
      console.log(this.name); //xiaoming
    }
    temp();
  }
  var name = 'global';
  newFunc.call({name: 'xiaoming'});

这里我们发现箭头函数是可以绑定this的,它是怎么实现的呢?

  var newFunc = function () {
    var _this = this; //保存this
    var temp = function () {
      console.log("=========polyfill===========");
      console.log(_this); //Object {name: "xiaoming"}
      console.log(_this.name); //xiaoming
    }
    temp();
  }

  var name = 'global'; //Object {name: "xiaoming"}
  newFunc.call({name: 'xiaoming'}); //xiaoming

所以箭头函数本身是没有this的,而是绑定了this。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值