0
点赞
收藏
分享

微信扫一扫

重写Function.prototype.bind

颜路在路上 2021-09-25 阅读 63
前端

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

参数 thisArg
  • 如果使用 new 运算符构造绑定函数,则忽略该值。
  • 当使用 bind 在 setTimeout 中创建一个函数(作为回调提供)时,作为 thisArg 传递的任何原始值都将转换为 object。
  • 如果 bind 函数的参数列表为空,执行作用域的 this 将被视为新函数的 thisArg。
参数 arg1、arg2...

当目标函数被调用时,被预置入绑定函数的参数列表中的参数。

返回值

返回一个原函数的拷贝,并拥有指定的 this 值和初始参数。

重写 bind 方法

var point = {
    x: 0,
    y: 0,
    z: 0
}

// 构造函数
function Point(x, y, z) {
    console.log(this.x, x, y, z)
    console.log('')
}

// 函数名写成 bindy,是为了方便与原生 bind 方法对比
Function.prototype.bindy = function(context) {
    var _this = this;
    var args = Array.prototype.slice.call(arguments, 1);
    var tempFn = function() {};

    var fn = function() {
        var thatArgs = Array.prototype.slice.call(arguments)
        _this.apply(this instanceof _this ? this : context, args.concat(thatArgs))
    }

    // 圣杯模式
    tempFn.prototype = this.prototype;
    fn.prototype = new tempFn();

    return fn;
}

// bind 可以在调用的时候传入参数
Point.bind(point, 1, 2)(3);     // output: 0 1 2 3
Point.bindy(point, 4, 5)(6);    // output: 0 4 5 6

// 使用 new 去构造时,bind 绑定的 this 最终会执行构造函数
let p = Point.bind(point);
let p2 = Point.bindy(point);
new p(3, 3, 3);                 // output: undefined 3 3 3
new p2(4, 4, 4);                // output: undefined 4 4 4
举报

相关推荐

0 条评论