0

I am reading Kyle Simpson's You Don't Know JS: ES6 & Beyond and have a question about the first chapter: https://github.com/getify/You-Dont-Know-JS/blob/master/es6%20%26%20beyond/ch1.md

I'm at the secion called Shims/Polyfills

There Object.is defined as:

if (!Object.is) {
    Object.is = function(v1, v2) {
        // test for `-0`
        if (v1 === 0 && v2 === 0) {
            return 1 / v1 === 1 / v2;
        }
        // test for `NaN`
        if (v1 !== v1) {
            return v2 !== v2;
        }
        // everything else
        return v1 === v2;
    };
}

and I tried it out for several cases:

Object.is(‘abc’, ‘abc’);

Object.is(1/0, Infinity);

Object.is(NaN, NaN);

and it works well. However, I have the idea of making this an object-level function as well:

Object.prototype.is = function(value) {
    return Object.is(this, value);
}

yet, if I call

Object.is('abc', 'abc')

this correctly returns true. If I call

'abc'.is('abc')

this returns false. Can someone explain why my Object.prototype.is is not equivalent to Object.is?

EDIT:

Strict mode solves the problem:

"use strict";
if (!Object.is) {
    Object.is = function(v1, v2) {
        // test for `-0`
        if (v1 === 0 && v2 === 0) {
            return 1 / v1 === 1 / v2;
        }
        // test for `NaN`
        if (v1 !== v1) {
            return v2 !== v2;
        }
        // everything else
        return v1 === v2;
    };
}
Object.prototype.is = function(value) {
    return Object.is(this, value);
}

'abc'.is('abc'); //true
vzwick
  • 11,008
  • 5
  • 43
  • 63
Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175

0 Answers0