鍍金池/ 問(wèn)答/HTML/ 為什么析構(gòu)url對(duì)象會(huì)出現(xiàn)意想不到的結(jié)果

為什么析構(gòu)url對(duì)象會(huì)出現(xiàn)意想不到的結(jié)果

在學(xué)習(xí)Node.js的過(guò)程中,想要復(fù)制一個(gè)url對(duì)象引用,結(jié)果不盡人意,細(xì)節(jié)如下:

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

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

而析構(gòu)重建確實(shí)這樣的對(duì)象:

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 {} }
回答
編輯回答
撥弦
  1. new URL('file://') 是創(chuàng)建了一個(gè)URL實(shí)例對(duì)象(這里的URL相當(dāng)于類Class)
  2. { ...new URL('file://') }解構(gòu)賦值是把URL對(duì)象的屬性取出來(lái)重新創(chuàng)建了一個(gè)對(duì)象
  3. 前者是URL的實(shí)例, 后者只是一個(gè)普通對(duì)象, 所以它倆本質(zhì)上一點(diǎn)關(guān)系沒有
2017年10月16日 20:08
編輯回答
久礙你

有個(gè)簡(jiǎn)單的例子,在 node 環(huán)境下運(yùn)行。

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: {} }

關(guān)鍵就在這個(gè) util.inspect.custom 上。

2017年4月5日 21:21