试图弄清楚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()源...谢谢!