Call 'hasOwnProperty' on a reponse (fetch-api)

286 Views Asked by At

I know this is kinda dumb/useless, but I would love to understand it. I tried to call hasOwnProperty on a response-object but it always returns false. Why?

(await fetch('http://dummy.restapiexample.com/api/v1/employees')).hasOwnProperty('status');
2

There are 2 best solutions below

0
On BEST ANSWER

In Chrome, at least, the status property is not actually an own-property, but a getter on the prototype:

fetch('https://stacksnippets.net/js', { mode: 'no-cors' })
  .then((response) => {
    console.log(
      response.hasOwnProperty('status'),
      Object.getPrototypeOf(response).hasOwnProperty('status'),
      Object.getPrototypeOf(response) === Response.prototype
    );
    console.log(Object.getOwnPropertyDescriptor(Response.prototype, 'status'));
  });

So by referencing response.status, you'll be invoking the getter, despite the fact that the response does not have status as an own-property.

Error objects in some environment behave the same way - in earlier versions of Firefox, for example, the .message property is a property of Error.prototype, rather than being an own property of the error instance.

1
On
fetch('http://dummy.restapiexample.com/api/v1/employees')
  .then(response => response.json())
  .then(data => console.log(data.hasOwnProperty('status')));