示例工程 04-functions-this

04-functions-this/02-lost-this/main.test.mjs

javascript · 1.0 KB

运行:04 · this 丢失与修复

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

import { test } from 'node:test';
import assert from 'node:assert/strict';
import {
  detachedMethod,
  fixedByBind,
  fixedByCallAtCallSite,
  fixedByWrapper,
  passedAsCallback,
  run,
} from './main.js';
 
test('把方法取出来单独调用:this 变成 undefined,抛 TypeError', () => {
  assert.equal(detachedMethod(), 'TypeError');
});
 
test('方法直接当回调传给 map:同样丢 this', () => {
  assert.equal(passedAsCallback(), 'TypeError');
});
 
test('修复 1:箭头函数包装,保留外层 this', () => {
  assert.equal(fixedByWrapper(), '10,20');
});
 
test('修复 2:bind 固定 this', () => {
  assert.equal(fixedByBind(), '10,20');
});
 
test('修复 3:调用点用 call 指定 this', () => {
  assert.equal(fixedByCallAtCallSite(), 12);
});
 
test('run 输出 5 行场景与两条说明', () => {
  const out = [];
  const rows = run((s) => out.push(s));
  assert.equal(rows.length, 5);
  assert.equal(out.length, 8);
  assert.match(out[1], /TypeError/);
});