示例工程 03-variables-scope-hoisting
03-variables-scope-hoisting/03-function-hoisting/main.test.mjs
点击「运行示例」后,左侧显示源码、右侧显示运行结果;console 输出会实时回传。
import { test } from 'node:test';
import assert from 'node:assert/strict';
import {
blockFunctionVisibility,
callConstArrowBefore,
callDeclaredBefore,
callVarExpressionBefore,
run,
varRedeclare,
} from './main.js';
test('函数声明整体提升,可在定义前调用', () => {
assert.equal(callDeclaredBefore(), 'ok');
});
test('var 函数表达式:声明提升为 undefined,调用得到 TypeError', () => {
assert.equal(callVarExpressionBefore(), 'TypeError');
});
test('const 箭头函数:TDZ 中调用得到 ReferenceError', () => {
assert.equal(callConstArrowBefore(), 'ReferenceError');
});
test('严格模式下块级函数声明不会泄漏到块外', () => {
assert.equal(blockFunctionVisibility(), 'ReferenceError');
});
test('var 允许重复声明,后者覆盖前者', () => {
assert.equal(varRedeclare(), 2);
});
test('run 输出 5 行场景与两条说明', () => {
const out = [];
const rows = run((s) => out.push(s));
assert.equal(rows.length, 5);
assert.equal(out.length, 8);
assert.equal(out[1], '函数声明在定义前调用 => ok');
assert.match(out.at(-1), /TDZ/);
});