admin管理员组

文章数量:1356304

On macOS 10.13.1 with Chrome 63.

I'm using Object.assign with new URL() as the source object but it always gives an empty object? This seems like strange behavior. Here is my code:

 let url = new URL('');
 console.log(url);
 let data = Object.assign({}, url);
 console.log(data);

Why is data an empty object whereas url has the plete URL object as below:

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

I also tried:

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

but it gives:

Uncaught TypeError: undefined is not a function

On macOS 10.13.1 with Chrome 63.

I'm using Object.assign with new URL() as the source object but it always gives an empty object? This seems like strange behavior. Here is my code:

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

Why is data an empty object whereas url has the plete URL object as below:

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

I also tried:

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

but it gives:

Uncaught TypeError: undefined is not a function

Share Improve this question edited Jan 14, 2018 at 17:24 Boann 50.1k16 gold badges124 silver badges152 bronze badges asked Jan 12, 2018 at 18:32 xkeshavxkeshav 54.1k47 gold badges181 silver badges251 bronze badges 5
  • 3 Have you looked at the documentation for that function, "used to copy the values of all enumerable own properties" – Patrick Evans Commented Jan 12, 2018 at 18:36
  • yes. just checked and find first time what means of that. now my question is how do the copy the property then? – xkeshav Commented Jan 12, 2018 at 18:42
  • Which specific properties are you trying to get from the URL instance? – guest271314 Commented Jan 12, 2018 at 18:50
  • You would need to loop over each of the properties (eg for...in), as all the properties are actually getters/setters and based off some internal variable. – Patrick Evans Commented Jan 12, 2018 at 18:50
  • every property I need except serachParams – xkeshav Commented Jan 12, 2018 at 18:52
Add a ment  | 

2 Answers 2

Reset to default 7

I suspect it's because the properties of URL are not enumerable. Notice when you do Object.keys(url) you also get a blank array? Both Object.assign and Object.keys work with enumerable properties.

Properties on your url object are not enumerable.

You can clone URL by simply:

 let url = new URL('http://www.yahoo.');
 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.

本文标签: javascriptWhy does Objectassign not copy the properties of a URL objectStack Overflow