示例工程 03-variables-scope-hoisting

03-variables-scope-hoisting/03-function-hoisting/main.js

javascript · 1.8 KB

运行:03 · 函数声明与提升

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

// main.js —— 函数声明、函数表达式、箭头函数在提升上的差异
 
export function callDeclaredBefore() {
  return declared(); // 函数声明整体提升,可以在定义前调用
  function declared() {
    return 'ok';
  }
}
 
export function callVarExpressionBefore() {
  try {
    return expr();
  } catch (e) {
    return e.constructor.name; // TypeError:expr 已提升但值是 undefined
  }
  // eslint-disable-next-line no-unreachable
  var expr = function () {
    return 'no';
  };
}
 
export function callConstArrowBefore() {
  try {
    return arrow();
  } catch (e) {
    return e.constructor.name; // ReferenceError:const 绑定在 TDZ
  }
  // eslint-disable-next-line no-unreachable
  const arrow = () => 'no';
}
 
export function blockFunctionVisibility() {
  {
    function inner() {
      return 'in-block';
    }
    if (inner() !== 'in-block') throw new Error('块内应该可调用');
  }
  try {
    return inner();
  } catch (e) {
    return e.constructor.name; // 严格模式下块级函数不外泄
  }
}
 
export function varRedeclare() {
  var x = 1;
  var x = 2;
  return x;
}
 
export function run(log = console.log) {
  const rows = [
    ['函数声明在定义前调用', callDeclaredBefore()],
    ['var 函数表达式在赋值前调用', callVarExpressionBefore()],
    ['const 箭头函数在定义前调用', callConstArrowBefore()],
    ['块内函数声明在块外调用', blockFunctionVisibility()],
    ['var 重复声明', String(varRedeclare())],
  ];
  log('场景 => 结果');
  for (const [label, value] of rows) log(`${label} => ${value}`);
  log('-'.repeat(50));
  log('要点:function 声明整体提升;var 只提升声明(值为 undefined);const/let 提升但留在 TDZ;块级函数在严格模式下不外泄。');
  return rows;
}