0

Number is an intrinsic function object that is a function property on the globalThis.

console.log(Object.getOwnPropertyDescriptor(globalThis, 'Number')) // <descriptor>

Why, then, does globalThis.hasOwnProperty(window, 'Number') return false?

console.log(globalThis.hasOwnProperty(window, 'Number')) // false

I'm sure I am missing something obvious...

Ben Aston
  • 53,718
  • 65
  • 205
  • 331
  • 1
    [Object#hasOwnProperty](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty) receives one argument. –  Apr 07 '20 at 12:14
  • 1
    hasOwnProperty should be called like `window.hasOwnProperty('Number')` or `globalThis.hasOwnProperty('Number')` – Code Maniac Apr 07 '20 at 12:17
  • Doh! Oh dear.... – Ben Aston Apr 07 '20 at 12:19
  • 1
    It seems to be that your confusion comes from [the two different ways native functions/methods are defined](https://stackoverflow.com/q/13239317/1048572) – Bergi Apr 07 '20 at 12:24

2 Answers2

2

The error is in your call to hasOwnProperty it's a member function not a class function. So your call should be hasOwnPropery('Number') and now hasOwnPropery(window, 'Number') because globalThis does not have a window property and all later arguments will be ignored.

const globalThis = window;
console.log(Object.getOwnPropertyDescriptor(globalThis, 'Number'))
console.log(globalThis.hasOwnProperty('Number'))
Philip Rollins
  • 1,271
  • 8
  • 19
1

From the docs:

The hasOwnProperty() method returns a boolean indicating whether the object has the specified property as its own property (as opposed to inheriting it).

And the syntax is:

obj.hasOwnProperty(prop)

So, if you want to check: Is Number a window's property or not, you can try:

console.log(window.hasOwnProperty('Number')) // true
// or
console.log(globalThis.hasOwnProperty('Number')) // true

You don't need to provide the second parameter. Maybe you misread the way to use getOwnPropertyDescriptor and hasOwnProperty

Tân
  • 1
  • 15
  • 56
  • 102