I’m at a total loss.
I have a function..
Number.prototype.abs = function () {
return this >= 0 ? this : this * -1;
};
..that returns the absolute value of a number..
(50).abs(); // 50
(-50).abs(); // 50
..but that doesn’t compare correctly..
(50).abs() === 50; // False
..sometimes.
(50).abs() == 50; // True
(-50).abs() === 50; // True
The thing about it, is that it works in Chrome 12, and Firefox 4, but not in IE 9, Safari 5, or Opera 11.
I don’t see anything wrong with the code, and since it works in Chrome and Firefox, it’s something browser specific but I don’t know what.
Update: The browser specific difference is strict mode support. I run my code in strict mode, which introduces some changes that make my code work. The reason it failed in the browsers it did, is because they have an incomplete or missing strict mode.
Why is it returning false?
Even though Jeremy Heiler is correct, his justification is misconstrued. Why you’re getting
objectinstead ofnumberhas nothing to do with constructors.The problem here is the
thiskeyword. You need to understand what happens whenever you usethis. A little bit of digging through the ECMA draft will show you that(I would change the above. The
thiskeyword doesn’t evaluate to the value of anything as we’ll soon see.) Hmm, okay, but how exactly doesThisBindingwork? Read on!And therein lies the rub (look at the bolded part). If a function is ever called from a non-object context,
ThisBinding(aka usingthis) always returns the value of the context wrapped inside an object. The easiest way to fix it would be to do:…to coerce the
thisobject (or to force strict mode). But I think it’s important to understand howthisworks, and this question is a great example of that.