算法打卡day5——手写bind

24 阅读1分钟
Function.prototype.myBind(context, ...args){
    //无论在浏览器还是 Node.js 中,都可以使用 globalThis 来访问全局对象
    context = context || globalThis 
    const self_fn = this
    return function boundFn(...innerArgs){
        //判断是否作为构造函数调用(也可以通过this instanceof boundFn)
        if(new.target){
                return new self_fn(...args, ...innerArgs)
        }
        return self_fn.apply(context,args.concat(innerArgs))
    }
}

一开始我没有理解判断是否作为构造函数调用这里什么意思,大家没明白的可以看看下面这个例子:

function foo(x, y) { 
    this.name = "Fez";
    console.log(this.num, x + y)
} 
const obj = { num: 711 } 
const foo2 = foo.bind(obj, 1,2)
console.log(new foo2())

// undefined 6 (执行foo中代码)
// foo { name: '张三' } (foo本身)

可以看到我们new foo2实际上相当于去new了foo