call() 和 apply() 方法在上層應用中用得不多,但在底層編寫 JS 框架時卻很常見。查了不少資料後,各家的理解五花八門,於是又去 W3C 學習了一番。
在研究這兩個方法時,我注意到一個詞——「對象冒充」,這個概念挺重要,讓我對它們的理解更加直觀。
call() 方法,先看官方例子
function sayColor(sPrefix,sSuffix) { alert(sPrefix + this.color + sSuffix); }; var obj = new Object(); obj.color = "blue"; sayColor.call(obj, "The color is ", "a very nice color indeed."); 最終輸出:「The color is blue, a very nice color indeed.」。
可見 call() 就是把第一個參數替換方法中的 this,然後把後面的參數依次傳入該方法使用。
apply() 方法,同樣看個官方例子
function sayColor(sPrefix,sSuffix) { alert(sPrefix + this.color + sSuffix); }; var obj = new Object(); obj.color = "blue"; sayColor.apply(obj, new Array("The color is ", "a very nice color indeed.")); 輸出結果仍然是:「The color is blue, a very nice color indeed.」。
其實 call() 和 apply() 可以粗略地認為差不多:第一個參數都是替換方法中的 this 關鍵字,只是傳參方式不同——call 是直接一一對應傳參,apply 則是把參數放進數組裡一一對應。
以上就是關於 JavaScript 中 call() 和 apply() 的一些理解,希望對大家有所幫助。