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
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?
One close solution I have found is the one below. This will print properties with console.log(obj)
. However obj is a Proxy.
On chrome console the result is the same as XMLHttpRequest
output (with class being Proxy
). On firefox console it a representation of the Proxy
class, so it is not exactly the same.
const obj = new Proxy({prop1:"value1", prop2: "value2"}, {ownKeys: _=>[]});
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(obj)
result:
Object.keys(): []
Object.getOwnPropertyNames(): []
Object.entries(): []
JSON.stringify(): {}
console.log:
Proxy {prop1: "value1", prop2: "value2"}
and console.log(obj.prop1) / obj.prop1="newValue"
still works.