程序员成长-修炼中心 「作者:陈楚城」
导航
博客文章
  • Github (opens new window)
  • 掘金 (opens new window)
组件库 (opens new window)
关于我

chamberlain

前端持续学习者
导航
博客文章
  • Github (opens new window)
  • 掘金 (opens new window)
组件库 (opens new window)
关于我
  • 写在前面
  • vue3学习总结

  • 项目相关

  • 性能优化

  • 你不知道的css

  • 常见问题总结记录

  • 数据结构与算法

  • 设计模式

  • TS & JS进阶

  • Node

  • HTTP

  • Linux

  • 开发工具篇

  • 收藏夹

  • OS

  • Nginx

  • 项目工程化

  • 数据库

  • 计算机网络

  • 环境搭建、项目部署

  • 常用工具

  • 自动化

  • js相关

    • 函数柯里化curry
    • 继承
    • 使用setTimeout模拟setInterval
    • 手写防抖和节流
    • 手写实现拖拽
    • create
    • 手写一个call或apply
    • bind
      • 概念
      • 特点
      • 实现
    • 手写一个instanceOf原理
    • 手写一个JS深拷贝
    • parse和JSOn.stringify
    • 手写一个map和reduce
    • 手写一个new操作符
    • LRU缓存算法
    • 手写Promise
    • set
    • random
    • 原型
    • 实现Symbol类型
  • QA相关

  • 文章收藏

  • note
  • jsNote
chamberlain
2022-03-14
目录

bind

# 手写一个Function.bind

# 概念

bind()方法创建了一个新的函数,在bind被调用时,这个新的函数的this被指定为bind的第一个参数,而其余参数将作为新函数的参数,供调用时使用。

通俗一点,bind与apply、call一样都能改变函数this指向,但是bind并不会立即执行函数,而是返回了一个绑定了this的新函数,你需要再次调用此函数才能达到最终执行。

# 特点

  • 可以修改函数的this指向。
  • bind返回一个绑定this的新函数
  • 支持函数柯里化
  • 新的函数的this无法再被修改,使用call或者apply都不可以

# 实现

Function.prototype.bind = function (context) {
  let me = this;
  let args = Array.prototype.slice.apply(arguments,[1]);
  let F = function (){};
  F.prototype = me.prototype
  let bound = function () {
    let innerArgs = Array.prototype.slice.call(arguments);
    let finalArgs = args.concat(innerArgs)
    return me.apply(this instanceof F?this:context||this,finalArgs)
  }
  bound.prototype = new F();
  return bound;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
更新时间: 3/15/2022, 12:28:01 AM
手写一个call或apply
手写一个instanceOf原理

← 手写一个call或apply 手写一个instanceOf原理→

最近更新
01
02
网站
06-10
03
nav
06-09
更多文章>
Theme by Vdoing | Copyright © 2019-2022 chamberlain | MIT License
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式