如何使用Javascript';s URL()构造函数在幕后工作(getter/setter古怪)
试图弄清楚URL()构造函数(和其他本机Javascript API)的幕后发生了什么。当我尝试创建一个带有普通道具的对象,该道具也有一个设置器时,我会得到错误:如何使用Javascript';s URL()构造函数在幕后工作(getter/setter古怪),javascript,oop,Javascript,Oop,试图弄清楚URL()构造函数(和其他本机Javascript API)的幕后发生了什么。当我尝试创建一个带有普通道具的对象,该道具也有一个设置器时,我会得到错误: Uncaught TypeError: Invalid property descriptor. Cannot both specify accessors and a value or writable attribute 但请注意,通过实例化一个新URL(),您可以注销该对象,查看所有正常的可枚举道具,但这些道具具有自定义set
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()源。。。谢谢
解释很好,或者指向URL()源。。。谢谢
-->“它们仍然是常规的、可枚举的、非getter的道具”不,如果您查看原型,您会发现它们是setter和getter。如果您查看,您将看到它们引用了每个属性的getter/setter@PatrickEvans但是如果你对对象进行console.log,道具本身就是字符串;我看到原型有getter/setter。当我尝试复制此实现时,我的实例对象在实例上具有getter/setter函数原型包含实例获得的方法。。。。你把道具看成是弦,因为这就是getterreturns@PatrickEvans不幸的是,很难用文本来描述,但是当您在Chrome开发控制台中记录实例时,使用原生URL()实现时,道具显示为字符串。在我的实现中,在原型上使用getter/setter,它们显示为单击时解析的
(…)
。这是一个非常小的问题,因为typeof prop
仍然返回字符串。。。我只是好奇到底发生了什么不同的BTS