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

相关推荐
AAA阿giao2 小时前
Vue3 调用 Coze 工作流:从上传宠物照到生成冰球明星的完整技术解析
前端·vue.js·coze
异界蜉蝣2 小时前
React Fiber架构:Diff算法的演进
前端·react.js·前端框架
追梦_life2 小时前
localStorage使用不止于getItem、setItem、removeItem
前端·javascript
全栈陈序员2 小时前
请描述下你对 Vue 生命周期的理解?在 `created` 和 `mounted` 中请求数据有什么区别?
前端·javascript·vue.js·学习·前端框架
无限大62 小时前
用三行代码实现圣诞树?别逗了!让我们来真的
前端·javascript
init_23612 小时前
label-route-capability
服务器·前端·网络
拉姆哥的小屋2 小时前
深度剖析SentiWordNet情感词典:155,287单词的情感世界
前端·javascript·easyui
T___T2 小时前
从 0 搭建 React 待办应用:状态管理、副作用与双向绑定模拟
前端·react.js·面试
林太白2 小时前
vue3这些常见指令你封装了吗
前端·javascript