Javascript的URL()构造函数如何在幕后工作(getter / setter怪异)

时间:2017-10-21 23:31:27

标签: javascript oop

试图弄清楚URL()构造函数(以及其他本机Javascript API)的幕后发生了什么。当我尝试使用也具有setter的普通prop创建一个对象时,我收到错误:

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

但是通知实例化一个新的URL(),您可以注销该对象,查看所有正常的可枚举道具,但这些道具具有自定义的setter行为:

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'
  }

解释很棒或指向URL()源...谢谢!

1 个答案:

答案 0 :(得分:-2)

  

解释很棒或指向URL()源...谢谢!

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