You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

自定义可多次重绑定的bind函数无法通过Codewars测试求排查

问题排查:自定义可重复绑定的bind函数无法通过测试

问题描述

需要实现一个支持无限次重新绑定上下文的Function.prototype.bind,本地测试有效,但无法通过Codewars测试。

我的实现代码:

Function.prototype.bind = function (context) {
  if (!globalThis.func) {
    globalThis.func = this;
  }
  return function (...arg) {
    globalThis.func.call(context, ...arg);
  };
};

本地测试代码:

var func = function (a) {
  console.log("Argument is:", a);
  console.log("this = ", this);
  return this.prop;
};
var obj1 = { prop: 1 },
  obj2 = { prop: 2 };

func = func.bind(obj1);
func("Arg1");

func = func.bind(obj2);
func("Arg2");

问题根源

你的实现存在两个核心问题:

  1. 全局变量污染:用globalThis.func存储原始函数是全局共享的,多个函数同时使用bind时会互相覆盖,完全破坏函数的独立性——比如两个不同的函数调用bind后,会互相篡改对方的原始函数引用。
  2. 未处理多函数绑定场景:Codewars的测试必然包含多函数绑定的用例,你的全局变量方案在这种场景下会直接失效。

修正后的实现

正确的实现需要为每个绑定后的函数独立存储原始函数,避免全局污染,同时支持无限次重新绑定:

Function.prototype.bind = function(context) {
  // 获取原始函数:如果当前是已绑定的函数,取其存储的原始函数;否则就是当前函数本身
  const originalFn = this.__originalFn || this;
  // 创建新的绑定函数
  const boundFn = function(...args) {
    // 用最新绑定的上下文执行原始函数
    return originalFn.call(context, ...args);
  };
  // 给绑定函数添加属性,存储原始函数,方便后续再次绑定
  boundFn.__originalFn = originalFn;
  return boundFn;
};

验证测试

用你的本地测试代码验证:

  • 第一次绑定obj1后执行,this指向obj1,返回1
  • 第二次绑定obj2后执行,this指向obj2,返回2
    同时多个函数绑定不会互相干扰,完全满足题目要求。

内容的提问来源于stack exchange,提问作者Dmitry Strizhakov

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 09:37:05