js手寫call函數


Function.prototype.myCall = function (context, ...arr) {
    if (context === null || context === undefined) {
       // 指定為 null 和 undefined 的 this 值會自動指向全局對象(瀏覽器中為window)
        context = window 
    } else {
        context = Object(context) // 值為原始值(數字,字符串,布爾值)的 this 會指向該原始值的實例對象
    }
    const specialPrototype = Symbol('特殊屬性Symbol') // 用於臨時儲存函數
    context[specialPrototype] = this; // 函數的this指向隱式綁定到context上
    let result = context[specialPrototype](...arr); // 通過隱式綁定執行函數並傳遞參數
    delete context[specialPrototype]; // 刪除上下文對象的屬性
    return result; // 返回函數執行結果
};
let test = {
    name: "test"
}, fun = {
    fn: function () {
          console.log(this.name)
    }
}
fun.fn.myCall(test)
context[specialPrototype] = this; 這句話的個人理解
這個函數里面context是當你使用myCall的this指向對象
當你使用上面方法之后相當於在這個指向對象里面新增了一個key為specialPrototype,value為函數的this的鍵值對(this的指向問題,當你使用myCall的時候,this是調用myCall的函數,即上面的fun.fn,即最終是在context里面新增了一個specialPrototype:fun.fn)
context[specialPrototype](...arr);當你執行這行代碼的時候 其實是調用了fun.fn,但是這個時候 里面的this的指向變為調用specialPrototype的context
就這樣context中的this就完成代替了fun.fn中的this
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM