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

JavaScript自定义call Polyfill返回undefined问题求助

问题原因

你的myCall方法没有返回函数执行后的结果!原生的call会返回目标函数执行时的返回值,而你的代码里只是调用了context.fn(...args),但没有把这个调用的结果return出去,所以默认返回undefined。

另外还有个细节问题:你直接给context添加了fn属性,会污染原对象,最好执行完后删掉这个临时属性,避免影响原对象的结构。

修复后的Polyfill
Function.prototype.myCall = function(context, ...args) {
  // 处理context为null/undefined的情况,默认绑定全局对象
  context = context || globalThis;
  // 创建唯一的临时属性名,避免和原对象已有属性冲突
  const tempFn = Symbol('tempFn');
  context[tempFn] = this;
  // 执行函数并保存返回值
  const result = context[tempFn](...args);
  // 删除临时属性,清理对原对象的污染
  delete context[tempFn];
  // 返回函数执行的结果
  return result;
};
测试验证

修改后再运行你的测试代码:

console.log(printName.myCall(myName, "Kolkata", "India", "myCall"));
// 输出:myCall => Test Tester, Kolkata - India

这样就和原生call的行为完全一致了。

内容的提问来源于stack exchange,提问作者Faisal Rahman

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 16:43:56