Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>As defined in ECMA-262 ECMAScript Language Specification 3rd edition (see footnote), It's based on <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/call" rel="nofollow noreferrer">the spec</a> (Section 15.3.4.4):</p> <pre><code>var result = fun.call(thisArg[, arg1[, arg2[, ...]]]); </code></pre> <h1>Parameters</h1> <p><code>thisArg</code></p> <blockquote> <p>Determines the value of this inside fun. If thisArg is null or undefined, this will be the global object. Otherwise, this will be equal to Object(thisArg) (which is thisArg if thisArg is already an object, or a String, Boolean, or Number if thisArg is a primitive value of the corresponding type). Therefore, it is always true that typeof this == "object" when the function executes.</p> </blockquote> <p>Note in particular the last line.</p> <p>The crucial thing is that js primitives (<code>string</code>, <code>number</code>, <code>boolean</code>, <code>null</code>, <code>undefined</code>) are immutable, so a function can not be attached to them. Therefore the <code>call</code> function wraps the primitive in an <code>Object</code> so that the function can be attached.</p> <p>E.g.:</p> <p>Doesn't work:</p> <pre><code>var test = "string"; //the next 2 lines are invalid, as `test` is a primitive test.someFun = function () { alert(this); }; test.someFun(); </code></pre> <p>Works: </p> <pre><code>var test = "string"; //wrap test up to give it a mutable wrapper var temp = Object(test); temp.someFun = function () { alert(this); }; temp.someFun(); </code></pre> <p>(footnote) - as <a href="https://stackoverflow.com/users/113716/patrick-dw">patrick dw</a> noted in the comments, this will change in <a href="http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-262.pdf" rel="nofollow noreferrer">ECMA-262 ECMAScript Language Specification 5th edition</a> when in strict mode:</p> <blockquote> <p>From Section 15.3.4.4:</p> <blockquote> <p>NOTE The thisArg value is passed without modification as the this value. This is a change from Edition 3, where a undefined or null thisArg is replaced with the global object and ToObject is applied to all other values and that result is passed as the this value.</p> </blockquote> </blockquote>
 

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