函数的扩展

函数参数的默认值

基本用法

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

  log('Hello') // Hello World
  log('Hello', 'China') // Hello China
  log('Hello', '') // Hello World

与解构赋值默认值结合使用

  function fetch(url, { body = '', method = 'GET', headers = {} }) {
    console.log(method)
  }

  fetch('http://example.com', {}) // 'GET'

  fetch('http://example.com') // Uncaught TypeError: Cannot read property 'body' of undefined

解构赋值默认值的例子

  function fetch(url, { body = '', method = 'GET', headers = {} } = {}) {
    console.log(method)
  }

  fetch('http://example.com') // 'GET'

函数的length属性:指定了默认值以后,函数的length属性,将返回没有指定默认值的参数个数。也就是说,指定了默认值后,length属性将失真

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

某个参数指定默认值以后,预期传入的参数个数就不包括这个参数了。同理,rest参数也不会计入length属性。

  (function (...args) {}).length  // 0

如果设置了默认值的参数不是尾参数,那么length属性也不再计入后面的参数了。

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

rest参数

rest对象是一个真正的数组,数组持有的方法都可以使用。

  function push(array, ...items) {
    items.forEach(function(item) {
      array.push(item);
      console.log(item)
    })
  }

  var a = []
  push(a, 1, 2, 3)

严格模式

从ES5开始,函数内部可以设定为严格模式。ES2016做了一点修改,规定只要函数参数使用了默认值、解构赋值、或者扩展运算符,那么函数内部就不能显示设定为严格模式,否则会报错

  function doSomething(a, b) {
    'use strict';
    // code
  }

name属性

函数name属性,返回该函数的函数名

  function foo() {}
  foo.name

Function构造函数返回的函数实例,name属性的值为anonymous

  (new Function).name  // 'anonymous'

bind返回的函数,name属性值会加上bound前缀。

  function foo() {}
  foo.bind({}).name  // 'bound foo'

  (function() {}).bind({}).name  // 'bound'

箭头函数

注:

  • 函数体内的this对象,就是定义时所在的对象,而不是使用时所在的对象。
  • 不可以当做构造函数,也就是说,不可以使用new命令,否则会抛出一个错误。
  • 不可以使用arguments对象,该对象在函数体内不存在。如果要用,可以用rest参数代替。
  • 不可以使用yield命令,因此箭头函数不能用作Generator函数。

尾调用优化

什么是尾调用?

尾调用就是指某个函数的最后一步是调用另一个函数。

尾调用优化

  function factorial(n, total) {
    if (n === 1) return total
    return factorial(n - 1, n * total)
  }
  function Fibonacci(n, ac1 = 1, ac2 = 1) {
    if (n <= 1) return ac2

    return Fibonacci(n - 1, ac2, ac1 + ac2)
  }

函数参数的尾逗号

Function.prototype.toString()

catch命令的参数省略

  try {
    // ...
  } catch {
    // ...
  }
原文地址:https://www.cnblogs.com/shuilinger/p/12782079.html