手寫call apply bind函式

2022-09-07 08:33:16 字數 997 閱讀 7259

function.prototype.mcall = function (context, ...args)
context = context || window || global;

const funcname = symbol();

context[funcname] = this;

// 傳入的引數不是陣列

if (!array.isarray(args))

const res = args.length ? context[funcname](...args) : context[funcname]();

delete context[funcname];

return res;

}這裡有一些特殊,如果繫結後返回的新函式被使用new運算子呼叫,繫結時的this引數會被忽略

參考:

參考:

function person (name, age) 

const mperson = person.bind();

mperson('zhangsan', 18); //

new person('lisi', 19); // person ,繫結時的this被忽略

function.prototype.mbind = function (thisarg, ...args) 

// 或者下面這樣。`new.target`可以檢測函式是否是用`new`運算子呼叫的

if (new.target) }}

手寫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詳解

個人部落格 歡迎交流 螢火之森 三者都是改變函式執行時的上下文,也就是就是改變this的指向。函式.call 第乙個引數 想讓函式中this指向誰,就傳誰進來,後面的引數 本身函式需要傳遞實參,需要幾個實參,就乙個乙個的傳遞即可 call的作用 1.呼叫函式 2.指定函式中this指向 函式.bin...

手寫原始碼之 call,apply,bind

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