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

相关推荐
方安乐1 分钟前
react笔记之tanstack
前端·笔记·react.js
学嵌入式的小杨同学8 小时前
从零打造 Linux 终端 MP3 播放器!用 C 语言实现音乐自由
linux·c语言·开发语言·前端·vscode·ci/cd·vim
weixin_425543739 小时前
TRAE CN3.3.25 构建的Electron简易DEMO应用
前端·typescript·electron·vite·nestjs
Mr Xu_10 小时前
【Vue3 + ECharts 实战】正确使用 showLoading、resize 与 dispose 避免内存泄漏
前端·信息可视化·vue·echarts
0思必得010 小时前
[Web自动化] Selenium设置相关执行文件路径
前端·爬虫·python·selenium·自动化
雯0609~10 小时前
hiprint:实现项目部署与打印1-官网提供普通html版本
前端·html
不绝19111 小时前
UGUI——进阶篇
前端
Exquisite.11 小时前
企业高性能web服务器(4)
运维·服务器·前端·网络·mysql
2501_9445255412 小时前
Flutter for OpenHarmony 个人理财管理App实战 - 账户详情页面
android·java·开发语言·前端·javascript·flutter
2601_9498574312 小时前
Flutter for OpenHarmony Web开发助手App实战:快捷键参考
前端·flutter