最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

JavaScript Object.assign not working on Date object - Stack Overflow

programmeradmin7浏览0评论

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
Add a ment  | 

1 Answer 1

Reset to default 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.

发布评论

评论列表(0)

  1. 暂无评论