Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>When you call "apply" on a function, the function object itself is the "this" of the call to "apply", so you can do this:</p> <pre><code>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. </code></pre> <p>Basically, we are forcing the use of <code>Function.prototype.apply</code> instead of trying to look for a non-existing <code>setTimeout.apply</code>. In the parameters to <code>call</code>, the first argument is the function we want to run using <code>apply</code> (the object context, which is <code>setTimeout</code> in this case). What follows next are the parameters that get pass to <code>apply</code>, the first of which is the expect <code>this</code> the function will be run under ('null' in this case, since <code>setTimeout</code> does not allow a <code>this</code> context value), and the following being the array of arguments to be passed to the function we want to run.</p> <p>This works in IE7+, except IE7 doesn't pass on the custom parameters (i.e 'abc' in this example, which will prompt "undefined" instead).</p> <p>Here's a TypeScript implementation:</p> <pre><code>/** 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); } } </code></pre> <p>... and a basic JavaScript one:</p> <pre><code>function apply(func, _this, args) { if (func.apply) { return func.apply(_this, args); } else { return Function.prototype.apply.call(func, _this, args); } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload