手寫call apply bind詳解

2021-10-25 10:38:25 字數 1564 閱讀 7298

個人部落格**歡迎交流:螢火之森:

三者都是改變函式執行時的上下文,也就是就是改變this的指向。

函式.call(第乙個引數:想讓函式中this指向誰,就傳誰進來,

後面的引數:本身函式需要傳遞實參,需要幾個實參,就乙個乙個的傳遞即可);

call的作用: 1. 呼叫函式 2.指定函式中this指向

函式.bind(第乙個引數:想讓函式中this指向誰,就傳誰進來,

後面的引數:本身函式需要傳遞實參,需要幾個實參,就乙個乙個的傳遞即可)

bind的作用: 1. 轉殖當前函式,返回轉殖出來的新的函式

2. 新轉殖出來的函式,這個函式的this被指定了

看下面例子就明白了:

let obj  = 

}let obj2 =

console.log(obj.say.call(obj2)); // 螢火之森

console.log(obj.say.bind(obj2)); // function()

function.prototype.mycall = function(mythis, ...args) 

const fn = symbol('fn')

mythis= mythis|| window

mythis[fn] = this

// this指向呼叫call的物件,即我們要改變this指向的函式

const result = mythis[fn](...args)

// 執行當前函式

delete mythis[fn]

// 刪除我們宣告的fn屬性

return result

// 返回函式執行結果

}

if (typeof this !== "function")

const fn = symbol('fn')

mythis= mythis|| window

mythis[fn] = this

// this指向呼叫call的物件,即我們要改變this指向的函式

const result = mythis[fn](...args)

// 執行當前函式

delete mythis[fn]

// 刪除我們宣告的fn屬性

return result

// 返回函式執行結果

}

function.prototype.mybind = function (mythis, ...args) 

const self = this

const fbound = function ()

// 繼承原型上的屬性和方法

fbound.prototype = object.create(self.prototype);

return fbound;

}

手寫call,apply,bind函式

涉及面試題 考慮兩點 function.prototype.mycall function context context context window 和上面的 一樣 context.fn this const args arguments slice 1 const result context...

手寫call apply bind函式

function.prototype.mcall function context,args context context window global const funcname symbol context funcname this 傳入的引數不是陣列 if array.isarray ar...

手寫原始碼之 call,apply,bind

function.prototype.mycall function context,args let fnsymbol symbol context fnsymbol this let fn context fnsymbol args delete context fnsymbol return ...