示例工程 04-functions-this

04-functions-this/04-custom-bind/main.js

javascript · 2.5 KB

运行:04 · 手写 bind

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

// main.js —— 手写 bind:固定 this、预置参数、支持 new
// 与原生 Function.prototype.bind 的行为并排对照。
 
export function myBind(fn, context, ...preset) {
  if (typeof fn !== 'function') {
    throw new TypeError('bind 的目标必须是函数');
  }
 
  function bound(...args) {
    if (new.target) {
      // 被 new 调用时忽略 context,用原函数构造;new.target 语义交回原函数
      return Reflect.construct(fn, [...preset, ...args]);
    }
    return fn.apply(context, [...preset, ...args]);
  }
 
  return bound;
}
 
function greet(greeting, name) {
  return `${greeting}, ${this.title} ${name}`;
}
 
function Point(x, y) {
  this.x = x;
  this.y = y;
}
 
export function fixedThisAndPartialArgs() {
  const custom = myBind(greet, { title: 'Dr.' }, 'Hello');
  const native = greet.bind({ title: 'Dr.' }, 'Hello');
  return { custom: custom('Ada'), native: native('Ada') };
}
 
export function newIgnoresContext() {
  const Custom = myBind(Point, { title: 'ignored' }, 1);
  const Native = Point.bind({ title: 'ignored' }, 1);
  const c = new Custom(2);
  const n = new Native(2);
  return {
    custom: `${c.x},${c.y}`,
    native: `${n.x},${n.y}`,
    customIsPoint: c instanceof Point,
    nativeIsPoint: n instanceof Point,
  };
}
 
export function bindNonFunction() {
  try {
    myBind({}, null);
    return '没有抛错';
  } catch (e) {
    return e.constructor.name;
  }
}
 
export function arrowTargetWithNew() {
  const Custom = myBind(() => {}, null);
  try {
    new Custom();
    return '没有抛错';
  } catch (e) {
    return e.constructor.name; // Reflect.construct 拒绝非构造函数
  }
}
 
export function run(log = console.log) {
  const r1 = fixedThisAndPartialArgs();
  const r2 = newIgnoresContext();
  const rows = [
    ['自定义 bind:固定 this + 预置参数', r1.custom],
    ['原生 bind:同样调用', r1.native],
    ['new 自定义 bound:忽略 context', r2.custom],
    ['new 原生 bound:忽略 context', r2.native],
    ['instanceof Point(自定义)', String(r2.customIsPoint)],
    ['instanceof Point(原生)', String(r2.nativeIsPoint)],
    ['bind 非函数', bindNonFunction()],
    ['new 一个 bound 的箭头函数', arrowTargetWithNew()],
  ];
  log('场景 => 结果');
  for (const [label, value] of rows) log(`${label} => ${value}`);
  log('-'.repeat(50));
  log('要点:bind 返回新函数;调用时用 apply 注入 this,new 时用 Reflect.construct 交回原构造函数。');
  return rows;
}