Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>There's a difference between a primitive <a href="http://www.ecma-international.org/ecma-262/5.1/#sec-4.3.16" rel="nofollow">string value</a> and a <a href="http://www.ecma-international.org/ecma-262/5.1/#sec-4.3.15" rel="nofollow"><code>String</code> object</a>. </p> <pre><code>'foo' // primitive new String('foo') // object </code></pre> <p>When you call a String member function on a string primitive, it gets wrapped in a String object, which becomes the value of <code>this</code> within the function. (More on this behavior below.)</p> <p>So, in <code>removeExtension</code>, <code>this</code> is a <code>String</code> object. On the other hand, the built-in function <code>this.substr</code> returns a primitive; that's just how it's defined. Thus, you see different things when you return <code>this</code> (<code>String</code> <em>object</em>) versus the result of <code>this.substr</code> (string <em>primitive</em>). If you want to return a string primitive version of the <code>this</code> object, just use <code>this.toString</code>.</p> <p>You see the same wrapping behavior with any primitive, e.g., <code>Number</code>s:</p> <pre><code>Number.prototype.returnThis = function() { return this; } typeof 2; // 'number' typeof (2).returnThis() // 'object' (a Number object, specifically) </code></pre> <p>If you really want to know why this happens, it's in the ECMAScript spec:</p> <blockquote> <p><strong>10.4.3 Entering Function Code</strong></p> <p>The following steps are performed when control enters the execution context for function code contained in function object F, a caller provided thisArg, and a caller provided argumentsList:</p> <ol> <li>If the function code is strict code, set the <code>ThisBinding</code> to <code>thisArg</code>.</li> <li>Else if thisArg is null or undefined, set the <code>ThisBinding</code> to the global object.</li> <li>Else if <code>Type(thisArg)</code> is not Object, set the <code>ThisBinding</code> to <code>ToObject(thisArg)</code>.</li> <li>....</li> </ol> </blockquote> <p>Point #3 is the important on there: calling functions on primitive values (i.e., non-object) coerces them into their corresponding object form.</p>
    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