Why do deconstructing url objects have unexpected results

in the process of learning Node.js, I want to copy a url object reference, but the result is not satisfactory. The details are as follows:

console.log(new URL("file://"))

// URL {
//   href: "file:///",
//   origin: "null",
//   protocol: "file:",
//   username: "",
//   password: "",
//   host: "",
//   hostname: "",
//   port: "",
//   pathname: "/",
//   search: "",
//   searchParams: URLSearchParams {},
//   hash: "" }

and destructional reconstruction is indeed such an object:

console.log({ ...new URL("file://") })

// { [Symbol(context)]:
//   URLContext {
//     flags: 400,
//     scheme: "file:",
//     username: "",
//     password: "",
//     host: "",
//     port: null,
//     path: [ "" ],
//     query: null,
//     fragment: null },
//  [Symbol(query)]: URLSearchParams {} }
Mar.12,2021

has a simple example that runs in the node environment.

const util = require('util');
class Demo {
  constructor () {
    this.context = {key1: 1, key2: 2}
    this.query = {}
  }
  [util.inspect.custom] () {
    var obj = {}
    obj.key1 = this.context.key1
    obj.key2 = this.context.key2
    obj.result = ''
    return obj
  }
}
const demo = new Demo()
console.log(demo) // { key1: 1, key2: 2, result: '' }
console.log({...demo}) // { context: { key1: 1, key2: 2 }, query: {} }
The key to

lies in this util.inspect.custom .

Menu