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

相关推荐
有一个好名字27 分钟前
Agent Loop —— 一切从那个 while 循环开始
前端·javascript·chrome
一天睡25小时28 分钟前
Claude Code 指令入门教程
前端
yingyima1 小时前
正则表达式实战:从日志中精准提取关键字段
前端
TeamDev1 小时前
如何在 DotNetBrowser 中使用本地 AI 模型
前端·后端·.net
谢尔登1 小时前
10_从 React Hooks 本质看 useState
前端·ubuntu·react.js
辰同学ovo1 小时前
从全局登录状态管理学习 Redux
前端·javascript·学习·react.js
陈随易2 小时前
2年没用Nodejs了,Bun很香
前端·后端·程序员
donecoding2 小时前
Corepack 完全解析:从懵到懂,包管理器自由了
前端·node.js·前端工程化
yqcoder2 小时前
端经典面试题:为什么 0.1 + 0.2 !== 0.3?
前端·css
ZC跨境爬虫2 小时前
跟着 MDN 学 HTML day_12:(HTML网页图片嵌入)
前端·javascript·css·ui·html