js 手写bind

  1. bind返回一个函数
  2. 闭包保存this, 执行的时候用apply或call绑定this
  3. js中new的优先级高于bind
    Function.prototype._bind = function (context) {
        if (typeof this !== "function") throw "type error"
        const fn = this
        return function O() {
            // console.log(this instanceof O ? this : context);
            return fn.apply(this instanceof O ? this : context, [...arguments])
        }
    }

    function f() { 
        return 1
    }
    console.log(f._bind({ a: 1 })());  // 1
    console.log(new (f._bind({ a: 1 }))()); // O{}
posted @ 2022-06-14 18:24  IslandZzzz  阅读(27)  评论(0编辑  收藏  举报