function

作者: zdxhxh | 来源:发表于2019-11-05 09:45 被阅读0次

二、 函数

1. 默认值

ES5中,没有函数的默认值,所以只能var a = a || 'a'

function es6(a='a') { }
// 相当于
function es6(a) { 
  let a = a || 'a'  // 记住
}

推荐定义了默认值的参数 在函数的尾函数

指定了函数的默认值后,函数的length属性失效

2. 解构参数

function es6({a,b='b'}) { }
function m1({x = 0, y = 0} = {}) {
  /**
   * let arguments = arguments ? Object.assign({x=0,y=0},arguments) : {}
   * 
   * /
  return [x, y];
}

当默认值为函数时

function bar(func = () => foo) {
  let foo = 'inner';
  console.log(func());
}
bar() // ReferenceError: foo is not defined

// 分析
function bar(func = () => foo) {
  let func = ()=> foo   // 直接死亡
  // TDZ
  let foo = 'inner';
  console.log(func());
}

3. 惰性求值

let p = 1 
function es6(a=p+1) { 
  console.log(a)
}
es6() // logs 2
p =2 
es6() // logs 3

4. 箭头函数

function() { 

}

({形参})=>{ // ... }

arg => (arg === 1)

箭头函数具有使context静态化的表现(所以不要把他做成类的成员函数)

5. 剩余参数(rest 参数)

function show(a,b,...arg) { 
  console.log(arg)
}
  • rest参数是数组,而不是类数组
  • rest参数不计入函数的length

剩余参数必须在最后面

相关文章

网友评论

      本文标题:function

      本文链接:https://www.haomeiwen.com/subject/alcsbctx.html