Function.prototype.bind实现

目标

实现函数Function.prototype.mybind,效果等同于Function.prototype.bind

bind接受参数为:(thisArg, ...args)

实现

利用apply函数实现:

js 复制代码
Function.prototype.mybind = function(thisArg, ...args) {
  const fn = this;
  
  function bound(...innerArgs) {
    const context = (this instanceof bound) ? this : thisArg;
  
    return fn.apply(context, [...args, ...innerArgs]);
  }
  
  if (fn.prototype){
    bound.prototype = Object.create(fn.prototype);
    bound.prototype.constructor = bound;
  }

  return bound;
}

这里有一个细节,当得到了bound = fn.bind(obj1)后,再次调用bound2 = bound.bind(obj2),会忽略这个bind调用,bound2bound运行时的this都指向obj1。该行为手写bind与原始bind表现一致。

问题

bound.prototype应该为undefined

相关推荐
AlienZHOU20 小时前
DeepSeek Harness 插件:HTML 实时可视化编辑
前端·agent·deepseek
剪刀石头布啊1 天前
javascript手动实现继承
前端
Elias不吃糖1 天前
Langfuse 入门:Trace、Prompt、Dataset、Experiment、Evaluator
前端·python·prompt·langfuse
vipbic1 天前
一个前端的 9 天重构:我是怎么用 Codex 重做航栈的
前端·javascript·后端
Eason_Lou1 天前
【无标题】
前端·vue.js·html
_codemonster1 天前
npm run dev 是在开发模式运行,怎么在生产环境运行
前端·npm·node.js
kyriewen1 天前
我受够了复制报错去问 AI,花一下午给控制台做了个调试助手
前端·javascript·ai编程
IT_陈寒1 天前
Redis的DEL命令竟然没删掉数据?我踩的这个坑你得知道
前端·人工智能·后端
anOnion1 天前
构建无障碍组件之Menu and Menubar Pattern
前端·html·交互设计