関数で「apply」を呼び出すと、関数オブジェクト自体が「apply」の呼び出しの「this」になるため、次のことができます。
function test(s) { alert(""+s); }
Function.prototype.apply.call(setTimeout, null, [test, 0, 'abc']);
// Note: same as "setTimeout.apply(null, [test, 0, 'abc']);" in supported browsers.
Function.prototype.apply
基本的に、存在しないものを探す代わりに、の使用を強制していますsetTimeout.apply
。のパラメータcall
で、最初の引数は、使用して実行する関数apply
(この場合はオブジェクトコンテキストsetTimeout
)です。次に続くのは、に渡されるパラメーターですapply
。最初のパラメーターは、関数が実行されることを期待します(この場合、コンテキスト値を許可しないため、this
「null」 )。次は、への引数の配列です。実行したい関数に渡されます。setTimeout
this
これはIE7+で機能しますが、IE7はカスタムパラメーターを渡しません(つまり、この例では「abc」で、代わりに「undefined」というプロンプトが表示されます)。
TypeScriptの実装は次のとおりです。
/** Helps support cases where 'apply' is missing for a host function object (i.e. IE7 'setTimeout', etc.). This function
* will attempt to call '.apply()' on the specified function, and fall back to a work around if missing.
* @param {Function} func The function to call '.apply()' on.
* @param {Object} _this The calling object, which is the 'this' reference in the called function (the 'func' argument).
* Note: This must be null for special host functions, such as 'setTimeout' in IE7.
* @param {any} args The arguments to apply to given function reference (the 'func' argument).
*/
function apply(func: Function, _this: Object, args: any[]): any {
if (func.apply) {
return func.apply(_this, args);
} else {
return Function.prototype.apply.call(func, _this, args);
}
}
...そして基本的なJavaScriptのもの:
function apply(func, _this, args) {
if (func.apply) {
return func.apply(_this, args);
} else {
return Function.prototype.apply.call(func, _this, args);
}
}