Gili
Gili

Reputation: 90101

Why does Object.prototype.hasOwnProperty.call(Number, "toString") return false?

https://eslint.org/docs/rules/no-prototype-builtins and https://stackoverflow.com/a/12017703/14731 imply that:

However when running Chrome 75.0.3770.142 I see:

Questions:

  1. Shouldn't these return the same value?
  2. Where should I be using in this case assuming I am dealing with dynamic types that may or may not be equal to built-in?

Upvotes: 1

Views: 1551

Answers (1)

VLAZ
VLAZ

Reputation: 29086

You are actually checking two different things:

  • Number.prototype.hasOwnProperty("toString") will check if the prototype of the Number object contains the toString property and it doesn't come from its prototype chain (hasOwnProperty).
  • Object.prototype.hasOwnProperty.call(Number, "toString") is essentially the same as Number.hasOwnProperty("toString") - it's not checking the prototype but the Number object itself.

These are two different objects as can be seen here:

console.log(Number === Number.prototype)

So, the prototype is what contains the toString property and Number inherits it through that. So, in order to have equivalent check you need to check the prototype:

console.log(Number.prototype.hasOwnProperty("toString")); // = true
console.log(Object.prototype.hasOwnProperty.call(Number.prototype, "toString")); // = true

console.log(Number.hasOwnProperty("toString")); // = false - not on this object...
console.log("toString" in Number); // = true - ...so it it's inherited

Upvotes: 2

Related Questions