Regular objects can be cloned using this method:
a = {x:9}; //sample
b = Object.assign(Object.create(a),a);
console.log(a);
console.log(b);
However, the variables of Date type don't seem to work with Object.assign and Object.create:
a = new Date();
b = Object.assign(Object.create(a),a);
console.log(a);
console.log(b);
/*
Results of printing a, b are not the same:
a:
Thu Oct 20 2016 11:17:29 GMT+0700 (SE Asia Standard Time)
b:
Date {}
*/
I know I can create a clone of Date object another way using
b = new Date(a)
But why are Object.assign and Object.create not working on Date type?
Regular objects can be cloned using this method:
a = {x:9}; //sample
b = Object.assign(Object.create(a),a);
console.log(a);
console.log(b);
However, the variables of Date type don't seem to work with Object.assign and Object.create:
a = new Date();
b = Object.assign(Object.create(a),a);
console.log(a);
console.log(b);
/*
Results of printing a, b are not the same:
a:
Thu Oct 20 2016 11:17:29 GMT+0700 (SE Asia Standard Time)
b:
Date {}
*/
I know I can create a clone of Date object another way using
b = new Date(a)
But why are Object.assign and Object.create not working on Date type?
Share Improve this question asked Oct 20, 2016 at 4:20 Dan DDan D 8,6617 gold badges45 silver badges79 bronze badges 3- What is it that you're expecting to happen? What properties of the source Date object do you expect to be copied? – Pointy Commented Oct 20, 2016 at 4:23
- all of its properties – Dan D Commented Oct 20, 2016 at 4:25
- 2 Well it is copying over all of the enumerable and own properties. It's just that a Date instance doesn't have any. – Pointy Commented Oct 20, 2016 at 4:25
1 Answer
Reset to default 8The Object.assign()
method copies over the enumerable and own properties of the source object. A Date instance doesn't really have any of those (if you don't add any with your own code).
In particular, Date "properties" like the year, month, date, etc. aren't properties in the JavaScript sense. They're values that can be retrieved via the API. That doesn't make them properties.