示例工程 04-functions-this

04-functions-this/05-parameters/main.js

javascript · 2.6 KB

运行:04 · 参数:默认值、arguments 与 rest

点击「运行示例」后,左侧显示源码、右侧显示运行结果;console 输出会实时回传。

// main.js —— 参数:默认值、arguments 与 rest、没有重载、参数作用域
 
export function defaultValues() {
  function f(a, b = a * 2, c = b + 1) {
    return [a, b, c];
  }
  return {
    one: f(1),
    two: f(1, 5),
    three: f(1, 5, 9),
    explicitUndefined: f(1, undefined),
    explicitNull: f(1, null),
  };
}
 
export function defaultEvaluatedPerCall() {
  function getList(items = []) {
    return items;
  }
  return getList() === getList();
}
 
export function functionLength() {
  function a(x, y) {}
  function b(x, y = 1, z) {}
  function c(x, ...rest) {}
  return { a: a.length, b: b.length, c: c.length };
}
 
export function argumentsVsRest() {
  function oldStyle(a) {
    return {
      isArray: Array.isArray(arguments),
      length: arguments.length,
      third: arguments[2],
    };
  }
  function modern(a, ...rest) {
    return {
      isArray: Array.isArray(rest),
      length: rest.length,
      third: rest[1],
    };
  }
  return { oldStyle: oldStyle(1, 2, 3), modern: modern(1, 2, 3) };
}
 
export function noArityCheck() {
  function f(a, b) {
    return { a, b, count: arguments.length };
  }
  return { fewer: f(1), more: f(1, 2, 3) };
}
 
export function paramTdz() {
  try {
    (function (a = b, b = 2) {
      return a;
    })();
    return '没有抛错';
  } catch (e) {
    return e.constructor.name; // ReferenceError
  }
}
 
export function destructuredDefaults() {
  function f({ x = 0, y = 0 } = {}) {
    return [x, y];
  }
  return { none: f(), partial: f({ x: 1 }) };
}
 
export function run(log = console.log) {
  const d = defaultValues();
  const a = argumentsVsRest();
  const n = noArityCheck();
  const rows = [
    ['默认值:f(1)', JSON.stringify(d.one)],
    ['默认值:f(1, 5)', JSON.stringify(d.two)],
    ['默认值:f(1, undefined) 仍用默认值', JSON.stringify(d.explicitUndefined)],
    ['默认值:f(1, null) 不用默认值', JSON.stringify(d.explicitNull)],
    ['默认表达式每次调用重新求值', String(defaultEvaluatedPerCall())],
    ['function.length', JSON.stringify(functionLength())],
    ['arguments 不是数组', JSON.stringify(a.oldStyle)],
    ['rest 是数组', JSON.stringify(a.modern)],
    ['参数少传/多传都不报错', JSON.stringify(n)],
    ['参数默认值中的 TDZ', paramTdz()],
    ['解构参数默认值', JSON.stringify(destructuredDefaults())],
  ];
  log('场景 => 结果');
  for (const [label, value] of rows) log(`${label} => ${value}`);
  log('-'.repeat(50));
  log('要点:默认值只在实参为 undefined 时生效;参数个数不校验,缺的为 undefined,多的进 rest/arguments。');
  return rows;
}