简体   繁体   中英

How does Javascript's URL() constructor work behind the scenes (getter/setter weirdness)

Trying to figure out what's going on behind the scenes of the URL() constructor (and other native Javascript APIs). When I try to create an object with a normal prop that also has a setter, I get the error:

Uncaught TypeError: Invalid property descriptor. Cannot both specify accessors and a value or writable attribute

But notice with instantiating a new URL(), you CAN log out the object, see all the normal enumerable props, and yet those same props have custom setter behavior:

const u = new URL('http://google.com/example/path');
console.log(u);

  {
    // all of these are normal props:
    hostname: 'google.com',
    pathname: '/example/path',
    href: 'http://google.com/example/path'
  }

u.pathname = '/new-example/path';
console.log(u);

  {
    // notice that pathname AND href have changed, presumably from setter
    // behavior, but they're still regular, enumerable, non-getter props:
    hostname: 'google.com',
    pathname: '/new-example/path',
    href: 'http://google.com/new-example/path'
  }

Explanation would be great or point to URL() source... thanks!

Explanation would be great or point to URL() source... thanks!

URL API (MDN) --> URL Standard (WHATWG)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM