首页
  • 前端文章

    • JavaScript
  • 学习笔记

    • 《JavaScript高级程序设计》笔记
    • TypeScript
    • 小程序笔记
    • JS设计模式总结
  • 网络

    • 网络初探
    • http状态码
  • HTML
  • CSS
  • 技术文档
  • GitHub技巧
  • Nodejs
  • 博客搭建
  • 学习
  • 面试
  • 心情杂货
  • 实战例子
  • 实用技巧
关于
收藏
  • 分类
  • 标签
  • 归档
GitHub (opens new window)

Arthas

划水工程师
首页
  • 前端文章

    • JavaScript
  • 学习笔记

    • 《JavaScript高级程序设计》笔记
    • TypeScript
    • 小程序笔记
    • JS设计模式总结
  • 网络

    • 网络初探
    • http状态码
  • HTML
  • CSS
  • 技术文档
  • GitHub技巧
  • Nodejs
  • 博客搭建
  • 学习
  • 面试
  • 心情杂货
  • 实战例子
  • 实用技巧
关于
收藏
  • 分类
  • 标签
  • 归档
GitHub (opens new window)
  • 基础
  • 内置对象
  • 面向对象
  • 异步操作
  • DOM
  • 事件
  • 浏览器模型
  • 自行实现bind函数
  • web component
  • 《JavaScript教程》笔记
Arthas
2023-03-22

自行实现bind函数

Function.prototype.myBind = function (oThis) {
  if (typeof this !== "function") {
      throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
    }

    const aArgs = Array.prototype.slice.call(arguments, 1), 
        fToBind = this, 
        fNOP = function () {},
        fBound = function () {
          return fToBind.apply(
              this instanceof fNOP && oThis ? this : oThis || window,
              aArgs.concat(Array.prototype.slice.call(arguments))
          );
        };

    fNOP.prototype = this.prototype;
    fBound.prototype = new fNOP();

    return fBound;
  };

	const person = {
		name: 'John',
	};

	function sayHello(greeting) {
		console.log(greeting + ', ' + this.name);
	}
	const boundFunc = sayHello.myBind(person, 'Hello');
	boundFunc();
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
编辑 (opens new window)
上次更新: 2023/03/23, 17:39:26
浏览器模型
web component

← 浏览器模型 web component→

最近更新
01
webpack、vite性能优化
05-24
02
笔试题记录
05-23
03
如何超过大多数人
05-16
更多文章>
Theme by Vdoing | Copyright © 2023-2023 Arthas | MIT License
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式