简体   繁体   English

为什么Object.assign不复制URL对象的属性?

[英]Why does Object.assign not copy the properties of a URL object?

On macOS 10.13.1 with Chrome 63 . 在带有Chrome 63的 macOS 10.13.1上。

I'm using Object.assign with new URL() as the source object but it always gives an empty object? 我正在使用Object.assign新的URL()作为源对象,但它总是给出一个空对象? This seems like strange behavior. 这似乎是一种奇怪的行为。 Here is my code: 这是我的代码:

 let url = new URL('http://www.yahoo.com');
 console.log(url);
 let data = Object.assign({}, url);
 console.log(data);

Why is data an empty object whereas url has the complete URL object as below: 为什么数据是空对象,而url具有完整的URL对象,如下所示:

{
 href: "http://www.yahoo.com/", 
 origin: "http://www.yahoo.com", 
 protocol: "http:", 
 username: "", 
 password: ""
 ...
}

I also tried: 我也尝试过:

let data = Object.assign({}, ...url);  

but it gives: 但它给出了:

Uncaught TypeError: undefined is not a function 未捕获的TypeError:undefined不是函数

I suspect it's because the properties of URL are not enumerable . 我怀疑这是因为URL的属性不可enumerable Notice when you do Object.keys(url) you also get a blank array? 注意当你做Object.keys(url)你还得到一个空白数组? Both Object.assign and Object.keys work with enumerable properties. Object.assignObject.keys都使用enumerable属性。

Properties on your url object are not enumerable. 您的url对象上的属性不可enumerable.

You can clone URL by simply: 您可以通过以下方式克隆URL:

 let url = new URL('http://www.yahoo.com');
 console.log(url);
 let data = new URL(url);
 console.log(data);

URL syntax: 网址语法:

url = new URL(url, [base])

You can still use an existing URL object for the base, which stringifies itself to the object's href attribute. 您仍然可以使用现有的URL对象作为基础,它将自身字符串化为对象的href属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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