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
Object. assign() will copy everything into the new object, including any functions. Mutating the copied object also doesn't affect the original object.
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.
The Object.assign() method copies all enumerable own properties from one or more source objects to a target object.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With