Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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.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:

{
 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

like image 785
diEcho Avatar asked Jan 12 '18 18:01

diEcho


People also ask

Does object assign copy object?

Object. assign() will copy everything into the new object, including any functions. Mutating the copied object also doesn't affect the original object.

Does object assign copy reference?

Objects are assigned and copied by reference. In other words, a variable stores not the “object value”, but a “reference” (address in memory) for the value. So copying such a variable or passing it as a function argument copies that reference, not the object itself.

Which object methods can be used to copy all of the properties of an object into a new object?

The Object.assign() method copies all enumerable own properties from one or more source objects to a target object.


1 Answers

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.

like image 175
Pytth Avatar answered Oct 21 '22 07:10

Pytth