call,apply,bind

call

Function.prototype._call = function(targetObject) {
    if (typeof targetObject === 'undefined' || targetObject === null) {
        targetObject = window
    }
    targetObject = new Object(targetObject)

    const targetFnKey = 'targetFnKey'
    targetObject[targetFnKey] = this

    const result = targetObject[targetFnKey](...[...arguments].slice(1))
    delete targetObject[targetFnKey]
    return result
}

apply

Function.prototype._apply = function(targetObject, argsArray) {
    if (typeof argsArray === 'undefined' || argsArray === null) {
        argsArray = []
    }
    if (typeof targetObject === 'undefined' || targetObject === null) {
        targetObject = window
    }
    targetObject = new Object(targetObject)

    const targetFnKey = 'targetFnKey'
    targetObject[targetFnKey] = this

    const result = targetObject[targetFnKey](...argsArray)
    delete targetObject[targetFnKey]
    return result
}

bind

Function.prototype._bind =
    Function.prototype._bind ||
    function(context) {
        if (typeof this !== 'function') {
            throw new Error('Function.prototype.bind -not function')
        }
        var self = this
        //預(yù)設(shè)參數(shù)
        var args = Array.prototype.slice.call(arguments, 1)
        var F = function() {}
        F.prototype = this.prototype

        var fBind = function() {
            var innerArgs = Array.prototype.slice.call(arguments)
            var finalArgs = args.concat(innerArgs)
            return self.apply(this instanceof F ? this : context, finalArgs)
        }

        fBind.prototype = new F()
        return fBind
    }
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

  • 函數(shù)原型鏈中的 apply,call 和 bind 方法是 JavaScript 中相當(dāng)重要的概念,與 this ...
    OBKoro1閱讀 1,523評(píng)論 0 8
  • 綁定 this 的方法 參考文章:綁定 this 的方法 this的動(dòng)態(tài)切換,固然為 JavaScript 創(chuàng)造了...
    chrisghb閱讀 518評(píng)論 0 0
  • call,apply 在 javascript 中,call 和 apply 都是為了改變某個(gè)函數(shù)運(yùn)行時(shí)的上下文(...
    天降男神閱讀 323評(píng)論 0 0
  • 參考《JavaScript設(shè)計(jì)模式與開發(fā)實(shí)踐》 this 跟別的語言大相徑庭的是,JavaScript的this總...
    16manman閱讀 622評(píng)論 0 0
  • H 和我一起進(jìn)單位,已經(jīng)4年時(shí)間,現(xiàn)我們是很好的朋友,從她身上,我學(xué)到很多。 剛到單位的時(shí)候,我每天坐公交,她騎自...
    郵路閱讀 413評(píng)論 1 4

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