示例工程 05-objects-prototypes-class

05-objects-prototypes-class/01-manual-new/main.test.mjs

javascript · 1.8 KB

运行:05 · 手写 new

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

import { test } from 'node:test';
import assert from 'node:assert/strict';
import { myNew, run } from './main.js';
 
function Person(name) {
  this.name = name;
}
Person.prototype.greet = function () {
  return `hi ${this.name}`;
};
 
test('myNew 创建实例、挂原型、执行构造函数', () => {
  const p = myNew(Person, 'Ada');
  assert.equal(p.name, 'Ada');
  assert.equal(p.greet(), 'hi Ada');
  assert.equal(Object.getPrototypeOf(p), Person.prototype);
  assert.equal(p instanceof Person, true);
});
 
test('构造函数返回对象时,采用返回值', () => {
  function Factory() {
    this.discarded = true;
    return { replaced: true };
  }
  assert.deepEqual(myNew(Factory), { replaced: true });
});
 
test('构造函数返回原始值时,忽略返回值', () => {
  function Factory() {
    this.kept = true;
    return 42;
  }
  const obj = myNew(Factory);
  assert.equal(obj.kept, true);
  assert.equal(obj instanceof Factory, true);
});
 
test('prototype 不是对象时回退到 Object.prototype', () => {
  function F() {}
  F.prototype = null;
  const obj = myNew(F);
  assert.equal(Object.getPrototypeOf(obj), Object.prototype);
});
 
test('第一个参数不是函数时抛 TypeError', () => {
  assert.throws(() => myNew({}, 1), /必须是函数/);
});
 
test('原生 new 与 myNew 的原型行为一致', () => {
  const native = new Person('Bob');
  const manual = myNew(Person, 'Bob');
  assert.equal(Object.getPrototypeOf(native), Object.getPrototypeOf(manual));
  assert.deepEqual(Object.keys(native), Object.keys(manual));
});
 
test('run 输出 6 行场景与两条说明', () => {
  const out = [];
  const rows = run((s) => out.push(s));
  assert.equal(rows.length, 6);
  assert.equal(out.length, 9);
  assert.equal(out[3], '原型是否等于 Person.prototype => true');
});