js apply

今天因為工作上的需要
小小研究了一下apply 的用法

直接給個範例

function foo(x){
    console.log(x);
}

我們已經定義好一個函式 foo, 現在要用 apply 叫用它
則可以這樣寫 foo.apply(this, paras_array);

其中兩個參數

第一個參數是 this

一個英文的網站上解釋為
thisArg
The value of this provided for the call to fun. Note that this may not be the actual value seen by the method: if the method is a function in non-strict mode code, null and undefined will be replaced with the global object, and primitive values will be boxed.


第二個參數是函式的參數陣列
假設有三個參數, 那麼 paras_array 會是 [paras1, paras2, paras3]
apply 會自動將這些參數塞到對的位置

以本例來說,  foo.apply(this, ['1'])  意義等同於  foo('1')

留言

熱門文章