Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Even though <a href="https://stackoverflow.com/questions/6039265/50-50-false-50-50-true/6039320#6039320">Jeremy Heiler</a> is correct, his justification is misconstrued. Why you're getting <code>object</code> instead of <code>number</code> has nothing to do with constructors.</p> <p>The problem here is the <code>this</code> keyword. You need to understand what happens whenever you use <code>this</code>. A little bit of digging through the ECMA draft will show you that</p> <blockquote> <p>The this keyword evaluates to the value of the ThisBinding of the current execution context.</p> </blockquote> <p>(I would change the above. The <code>this</code> keyword doesn't evaluate to the <strong>value</strong> of anything as we'll soon see.) Hmm, okay, but how exactly does <code>ThisBinding</code> work? Read on!</p> <blockquote> <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 ThisBinding to thisArg.</li> <li>Else if thisArg is null or undefined, set the ThisBinding to the global object.</li> <li><strong>Else if Type(thisArg) is not Object, set the ThisBinding to</strong> <strong>ToObject(thisArg).</strong></li> <li>Else set the ThisBinding to thisArg.</li> <li>Let localEnv be the result of calling NewDeclarativeEnvironment passing the value of the [[Scope]] internal property of F as the argument.</li> <li>Set the LexicalEnvironment to localEnv.</li> <li>Set the VariableEnvironment to localEnv.</li> <li>Let code be the value of F’s [[Code]] internal property.</li> <li>Perform Declaration Binding Instantiation using the function code code and argumentList as described in 10.5</li> </ol> </blockquote> <p>And therein lies the rub (look at the bolded part). If a function is ever called from a non-object context, <code>ThisBinding</code> (aka using <code>this</code>) always returns the value of the context wrapped inside an object. The easiest way to fix it would be to do:</p> <pre><code>Number.prototype.abs = function () { "use strict"; // if available // * 1 implicitly coerces 'this' to a number value return this &gt;= 0 ? this * 1 : this * -1; //... or Number(this) explicitly coerces 'this' to its toNumber value return Number(this &gt;= 0 ? this : this * -1); }; </code></pre> <p>...to coerce the <code>this</code> object (or to force strict mode). But I think it's important to understand how <code>this</code> works, and this question is a great example of that.</p>
 

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