我有一個名爲myFunction()的函數。在JavaScript函數中定義「this」,併發送函數參數
在myFunction中,我希望「this」引用父項的「this」。
好吧,我會打電話給myFunction作爲myFunction.call(this)
。
太棒了!
糟糕,現在我需要傳遞一個參數給myFunction。通常情況下,我只會使用myFunction(myArg)
,但那種說法讓我感到困惑。
這怎麼辦?
我有一個名爲myFunction()的函數。在JavaScript函數中定義「this」,併發送函數參數
在myFunction中,我希望「this」引用父項的「this」。
好吧,我會打電話給myFunction作爲myFunction.call(this)
。
太棒了!
糟糕,現在我需要傳遞一個參數給myFunction。通常情況下,我只會使用myFunction(myArg)
,但那種說法讓我感到困惑。
這怎麼辦?
參數的參數後的第一個將作爲單獨的參數傳遞給你的函數documentation:
myFunction.call(this, argument_1, argument_2);
或者,你可以使用apply,它允許你將參數作爲一個數組(或一個像對象這樣的數組)傳遞給documentation:
myFunction.apply(this, argsArray);
感謝net.uk.sweet(也Adidi!)。我試過了,但第一次沒有奏效。讓我再試一次,直到它工作! – user1032531 2013-03-20 01:18:07
再次嘗試,它確實工作。操作員錯誤... – user1032531 2013-03-20 01:23:33
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Function/call – 2013-03-20 01:18:20