Javascript原生實現(xiàn)call/apply/bind

// call/apply/bind的原生js實現(xiàn)
// call和apply都是一次性且立即調(diào)用的
// bind是永久綁定到一個新函數(shù),并不會立即調(diào)用

// 原生js實現(xiàn)bind函數(shù)
// 所有的函數(shù)都要有bind方法,所以要定義在Function的原型對象上
Function.prototype.myBind = function(objThis,...params){
    // objThis是要綁定的this對象,...params是因為參數(shù)數(shù)量不確定才用解構(gòu)語法
    const thisFn = this;//當(dāng)前調(diào)用的函數(shù),例如fn.myBind()就把fn保存到thisFn
    let funcForBind = function(...secondParams){ // 要返回的函數(shù)
        // 判斷函數(shù)是否是用new function生成的
        const isNew = this instanceof funcForBind
        const thisArg = isNew?this:objThis //this的指向
        // 綁定好this和參數(shù)返回到外層,暫時用call綁定,call也可以原生實現(xiàn)
        return thisFn.call(thisArg,...params,...secondParams)
    }
    // 綁定原型
    funcForBind.prototype = Object.create(thisFn)
    return funcForBind //返回綁定好的函數(shù)
} 
// 原生js實現(xiàn)call函數(shù)
Function.prototype.myCall = function(objThis,...params){
    // 先判斷objThis,如果未傳入則將this指向window
    if(objThis===null || objThis==undefined){
        objThis = window
    }
    const specialMethod = Symbol('anything');//不重復(fù)的方法
    // 將這個不重復(fù)的方法作為objThis的一個屬性,屬性值就是要綁定this的那個函數(shù)
    objThis[specialMethod] = this // this就是需要綁定this的函數(shù)
    // 調(diào)用函數(shù)并且將結(jié)果返回
    let result = objThis[specialMethod](...params)
    // call是一次性的,所以調(diào)用完之后要刪除這個新增加的屬性
    delete objThis[specialMethod]
    return result // 返回結(jié)果
}
// 原生js實現(xiàn)apply函數(shù)
// apply函數(shù)與call函數(shù)基本一致的,只是傳入的參數(shù)是個數(shù)組
// 除了這兩行,都與call函數(shù)一致 
Function.prototype.myApply = function(objThis,arr){
    // ....
    let result = objThis[specialMethod](...arr) // 解構(gòu)傳入的數(shù)組
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容