1.call 方法:第乙個引數為 this 指向,第二個引數及以後 為傳入執行函式的引數。
function
mycall
(context)
function
(context)
const target =
this
; context = context ?
object
(context)
: window;
//當傳入的為 undefined/null 或者不傳那麼this預設指向window, 此處使用 object 轉換 是防止 傳入 原始資料型別 eg: number string 等
context.fn = target;
const result = context.fn(
...arg)
;delete context.fn;
return result
}
3.bind方法: 第乙個引數 為this指向,第二個引數及以後 為傳入執行函式的引數,並且執行之後會返回乙個繫結this 指向的函式
function
mybind
(context)
}
js中bind call apply的方法使用
在js中,這三者都是用來改變函式的this物件的指向的,他們有什麼樣的區別呢。在說區別之前還是先總結一下三者的相似之處 1 都是用來改變函式的this物件的指向的。2 第乙個引數都是this要指向的物件。3 都可以利用後續引數傳參。那麼他們的區別在 的,先看乙個例子。var xw var xh xw...
原生js實現bind call apply 二
this name 81 var obj var res obj.getname res 輸出 81 array 0 輸出array 0 是因為我沒有傳遞引數,所以params的長度為0這樣的呼叫方法,會因為 this 指向的問題得不到正確的值syw,所以要在呼叫時改變 this 指向,即可輸出正確...
bind call apply的區別與實現
三者都是用於改變函式體內this的指向,但是bindvar obj function test test false var testobj test.bind obj testobj true 以下是mdn文件 bind語法 call語法 語法 thisarg 在 fun 函式執行時指定的 thi...