在响应中调用“ hasOwnProperty”fetch-api

问题描述

我知道这有点傻/没用,但是我很想理解。我试图在响应对象上调用hasOwnProperty,但是它总是返回false。为什么?

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

解决方法

至少在Chrome中,status属性实际上不是自有财产,而是原型上的 getter

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'));
  });

因此,尽管响应中没有response.status作为自有财产,但通过引用status,您将调用getter。

某些环境中的错误对象的行为方式相同-例如,在早期版本的Firefox中,.message属性是Error.prototype的属性,而不是错误实例的自己的属性。

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