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

相关推荐
Ulyanov12 分钟前
高级可视化技术——让PyVista数据展示更专业
开发语言·前端·人工智能·python·tkinter·gui开发
开开心心_Every14 分钟前
重复图片智能清理工具:快速查重批量删除
java·服务器·开发语言·前端·学习·edge·powerpoint
Coffeeee15 分钟前
了解一下Android16更新事项,拿捏下一波适配
android·前端·google
亿元程序员22 分钟前
拖尾特效怎么实现?Cocos : 开箱即用!
前端
Wpa.wk22 分钟前
性能测试 - JMeter练习-JMeter录制Web端压测脚本操作步骤
java·前端·经验分享·jmeter·自动化
undefined在掘金3904124 分钟前
wpf 布局专题
前端
开开心心_Every24 分钟前
一键隐藏窗口到系统托盘:支持任意软件摸鱼
服务器·前端·python·学习·edge·django·powerpoint
m0_7482459224 分钟前
HTML 文本格式化
前端·html
winfredzhang26 分钟前
零基础打造轻量级桌面备忘录:Electron 核心技术实战
前端·javascript·electron·备忘录
dongczlu26 分钟前
聊聊GCD
前端