我知道这有点蠢/没用,但我很乐意理解它。我试图对一个响应对象调用hasOwnProperty,但它总是返回false。为什么?
(await fetch('http://dummy.restapiexample.com/api/v1/employees')).hasOwnProperty('status');发布于 2020-09-10 07:45:49
至少在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,您将调用getter,尽管响应没有将status作为自己的属性。
在某些环境中,错误对象的行为方式是相同的--例如,在火狐的早期版本中,.message属性是Error.prototype的属性,而不是错误实例的属性。
发布于 2020-09-10 07:42:51
fetch('http://dummy.restapiexample.com/api/v1/employees')
.then(response => response.json())
.then(data => console.log(data.hasOwnProperty('status')));https://stackoverflow.com/questions/63824999
复制相似问题