函数的扩展

ES6 - 函数的扩展

本节主要介绍了ES6关于函数的扩展,重点内容包括函数参数的默认值与箭头函数。

2021-01-25侠课岛    初级拔高       

前端/前端/前端系列课程P2 17     0     955

(五十五)ES6 - 函数的扩展

1:参数的默认值

function log(x, y = 'World') {
    console.log(x, y);
}

log('Hello');
/* Hello World */

log('Hello', 'China');
/* Hello China */

log('Hello', '');
/* Hello */

function week({ x, y = 5 }) {
    console.log(x, y);
}

week({});
/* undefined 5 */

week({x: 1});
/* 1 5 */

week({x: 1, y: 2});
/* 1 2 */

week();
/* TypeError: Cannot read property 'x' of undefined */

function week({x, y = 5} = {}) {
    console.log(x, y);
}

week();
/* undefined 5 */
  • 参数变量已经默认声明, 不能用let或const再次声明
  function week(x = 5) {
      let x = 1;
      const x = 2;
  }
  /* SyntaxError: Identifier 'x' has already been declared */
  • 函数不能有同名参数
  function week(x, x, y = 1) {
      /* ... */
  }
  /* SyntaxError: Duplicate parameter name not allowed in this context */
  • 参数默认值是惰性求值
  let x = 99;
  function week(p = x + 1) {
      console.log(p);
  }

  week();
  /* 100 */

  x = 100;
  week();
  /* 101 */
  • 参数默认值一般用于尾部

  • length属性 - 返回没有指定默认值的参数个数

  (function (a) {}).length;
  /* 1 */
  (function (a = 5) {}).length;
  /* 0 */
  (function (a, b, c = 5) {}).length;
  /* 2 */

  (function (a = 0, b, c) {}).length;
  /* 0 */
  (function (a, b = 1, c) {}).length;
  /* 1 */

  (function(...args) {}).length;
  /* 0 */
  • 设置了参数的默认值, 参数会形成一个单独的作用域
  var x = 1;

  function f(x, y = x) {
      console.log(y);
  }

  f(2);
  /* 2 */
let x = 1;

function f(y = x) {
    let x = 2;
    console.log(y);
}

f();
/* 1 */

function month(func = () => week) {
    let week = 'inner';
    console.log(func());
}

month();
/* ReferenceError: week is not defined */

var x = 1;
function week(x, y = function() { x = 2; }) {
    var x = 3;
    y();
    console.log(x);
}

week();
/* 3 */
x;
/* 1 */
function throwIfMissing() {
    throw new Error('Missing parameter');
}

function week(mustBeProvided = throwIfMissing()) {
    return mustBeProvided;
}

week();
/* Error: Missing parameter */
​```

本教程图文或视频等内容版权归侠课岛所有,任何机构、媒体、网站或个人未经本网协议授权不得转载、转贴或以其他方式复制发布或发表。

评价

17

本课评分:
  •     非常好
难易程度:
  •     适中的

内容目录


本文索引


|
教程
粉丝
主页

签到有礼

已签到2天,连续签到7天即可领取7天全站VIP

  • 1
    +2 金币
  • 2
    +3 金币
  • 3
    +5 金币
  • 6
    +7 金币
  • 5
    +6 金币
  • 4
    暖心福利
    自选分类VIP ×1天
  • 7
    惊喜大礼

    自选分类VIP ×3天 +20金币
  • 持续签到 +8 金币

金币可以用来做什么?