Sky
HOME
HOME
  • 前端笔记

    • CSS

      • 盒子模型
      • 屏幕单位
      • CSS 性能优化
    • JavaScript

      • Methods

        • Scheduler
        • Deep Clone
        • Curry
        • Calculation Function
        • debounce & throttle
      • Function bind
      • Array reduce
      • cross domain
      • event loop
      • ajax
      • event
      • context
      • inheritance
      • prototype
    • HTML

      • html render
      • forbidden <a>
      • <meta>
      • <script>
    • uni-app

      • scroll table

Function.prototype.bind | 绑定函数

  • 改变 this、预置参数、new 的表现

语法

    function.bind(thisArg[, arg1[, arg2[, ...]]])

参数

  • thisArg

    当绑定函数被调用时,该参数会作为原函数运行时的 this 指向。当使用 new 操作符调用绑定函数时,该参数无效

  • arg1, arg2, ...

    当绑定函数被调用时,这些参数将置于实参之前传递给被绑定的方法

实现

  1. 闭包的使用:保存私有变量 this 和 prefixArgs
  2. 判断是否通过 new 调用当前函数
  3. 使用 apply 在执行时改变函数的 this 指向
  4. 指向原函数的 prototype
  5. 返回函数

/**
 * 函数的bind方法
 * @param { object } context 上下文
 * @param { any } prefixArgs 参数
 * @returns { function } 返回函数
 * 
 * */

Function.prototype.bind = function (context, ...prefixArgs) {
    if (typeof this !== 'function') {
        throw new TypeError('Bind must be called on a function');
    }

    let self = this;
    let fBound = function (...args) {
        // 判断是否用了 new, 考虑new的情况
        if(this instanceof fBound) {
            return new self(...prefixArgs, ...args)
        }
        return self.apply(context, [...prefixArgs, ...args]);
    }
    // 让 bind 返回的新函数的 prototype 指向原函数的 prototype
    fBound.prototype = Object.create(self.prototype);
    return fBound;
}

最近更新: 2023/12/5 14:55
Contributors: liujw155@outlook.com
Next
Array reduce