4

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?

3
  • What is it that you're expecting to happen? What properties of the source Date object do you expect to be copied? Commented Oct 20, 2016 at 4:23
  • all of its properties 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. Commented Oct 20, 2016 at 4:25

1 Answer 1

8

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

Sign up to request clarification or add additional context in comments.

3 Comments

hm, JS is funny, it seems an instance of Date type is having "native" properties not accessible by JS code
@johnlowvale yes, that's entirely within the purview of native elements, though pure JavaScript code can have ways of doing that too. Object properties are right there as properties on the object, and as you can see from the MDN documentation there really aren't any on a Date instance.
Better to reference ECMA-262. Default Date instances have one internal property (their time value, accessible through getTime) and no own properties.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.