JavaScript之手写bind

60 阅读1分钟

JavaScript的Bind方法

bind 是 JavaScript 中的一个函数方法,它可以用来绑定函数的 this 值和参数,返回一个新的函数。

  • 绑定 this 值

在 JavaScript 中,函数的 this 值是在运行时确定的,它取决于函数的调用方式。如果不使用 bind 绑定 this 值,那么在函数被调用时,this 值可能会指向意外的对象或者 undefined。而使用 bind 可以在函数定义时就预先绑定好 this 值,确保函数被调用时 this 值始终指向正确的对象。

  • 绑定参数

除了绑定 this 值外,bind 还可以绑定函数的参数。这样可以在调用函数时,预先传入一些参数,使得函数的调用更加方便和简洁。

function fn(a,b,c,d){  
}
const newFn = fn.myBind('ctx',1,2)
newFn(3,4)
Function.prototype.myBind = function(ctx,...args){
    const fn = this
    return function(...subArgs){
        const allData = [...args,...subArgs]
        if(new.target){
            return new fn(...allData)
        }else{
        	return fn.apply(ctx,[...allData]) 
        }
    } 
}