Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why properties of an XMLHttpRequest object are only printable through console.log()?

var obj = new XMLHttpRequest();
console.log("Object.keys():",Object.keys(obj));
console.log("Object.getOwnPropertyNames():",Object.getOwnPropertyNames(obj))
console.log("Object.entries():",Object.entries(obj))
console.log("JSON.stringify():",JSON.stringify(obj))

console.log("console.log:"); console.log(obj)

output:

Object.keys(): []
Object.getOwnPropertyNames(): []
Object.entries(): []
JSON.stringify(): {}
console.log:
XMLHttpRequest {onreadystatechange: null, readyState: 0, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, …}

How can I create such an object in javascript, whose properties are only printed using console.log(obj), but not returned by any of the above functions?

I have already tried to create objects using constructor function, object.create() (with enumerable:false), Object.assign(), using getters, instatiating from a class, instatiating from an extended class e.t.c

like image 1000
Marinos An Avatar asked May 24 '18 10:05

Marinos An


People also ask

Which property of XMLHttpRequest represents the state of the request?

The readyState property holds the status of the XMLHttpRequest. The onreadystatechange property defines a callback function to be executed when the readyState changes.


1 Answers

This has to do with the WhatWG console.log specification:

How the implementation prints args is up to the implementation, but implementations should separate the objects by a space or something similar, as that has become a developer expectation.

The spec leaves the output format very vague and it's up to the implementation to decide what to print.

like image 68
Ján Jakub Naništa Avatar answered Sep 17 '22 18:09

Ján Jakub Naništa