[英]Why call to Function.apply.bind(fn, null) calls `fn.apply`, and not `Function.apply`?
假設我們有這樣的代碼:
let fn1 = Function.apply.bind(Math.max, null);
fn1([1, 10, 5]); // returns 10
我知道它是 ES6 中的一個spread function
,我們會這樣寫:
Math.max(...[1, 10, 5]);
但我無法理解Function.apply.bind
如何Function.apply.bind
它的魔力......
這就是我認為代碼工作的方式,請糾正我的錯誤。
let fn1 = Function.apply.bind(Math.max, null);
創建一個新的功能Function.apply(null)
與this
設定為Math.max
並將其分配給fn1
變量。fn1([1, 10, 5]);
調用我們的新創建的功能以這種方式: Function.apply(null, [1, 10, 5])
與this
將此功能設定為內部Math.max
。 但是這個調用是無效的……如果我們在 JS 控制台中復制/粘貼那一行 - 我們會得到Uncaught SyntaxError: Unexpected number
所以,我的問題是 - Function.apply
如何知道它應該使用this
等於Math.max
並“旋轉”/修改它對Math.max.apply
調用?
我才明白所有這些東西是如何工作的! 首先,讓我們將代碼重寫為其“真實”形式:
let fn1 = this.Function.apply.bind(Math.max, null);
this.fn1([1, 10, 5]); // returns 10
魔法? this
被隱式添加到“全局”方法/對象。 現在讓我們重寫這 2 段文字,向您展示魔法是如何工作的:)
let fn1 = Function.apply.bind(Math.max, null);
創建一個新函數newFunction.apply(null, ...args)
,其中newFunction == Math.max
,因此它與函數Math.max.apply(null, ...args)
並將其分配給fn1
變量.fn1([1, 10, 5]);
調用newFunction.apply(null, [1, 10, 5])
魔法揭曉:)
這個問題不是另一個問題的重復。 它不同,因為它更具體,在這里我特別問“為什么調用 Function.apply.bind(fn, null) 調用fn.apply
,而不是Function.apply
?” 而不是“apply.bind 是如何工作的?”。 這就像在問“為什么自行車齒輪使用踏板的動覺力而不是通過加速直接產生力”的問題? 與“自行車如何工作?”的問題相同。
讓我們把它分成幾部分,首先是bind()
:
bind()方法創建一個新函數,當調用
this
函數時,將其this
關鍵字設置為提供的值,在調用新函數時,在任何提供的參數之前都有給定的參數序列。
因此,您bind
Function
全局對象中的apply
方法bind
到Math.max
。
因此, bind()
返回的函數fn1
等效於this.apply()
,其中this
實際上是Math.max
,正如您對bind()
方法“詢問”的那樣。
這一行:
let fn1 = Function.apply.bind(Math.max, null);
……真的很麻煩。 :-)它要求bind
上Function.apply
,創建將調用一個函數apply
與Math.max
為this
值和null
作為第一個參數(thisArg apply
打電話時應該使用Math.max
; Math.max
沒有按”不關心this
,所以null
很好)。
當您調用fn1
,它會調用Function.apply
並將this
設置為Math.max
,並將null
作為第一個參數,然后是您傳遞給fn1
的數組。 apply
使用null
作為this
調用Math.max
,並將數組中的條目作為離散參數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.