简体   繁体   English

JavaScript Object.assign在Date对象上不起作用

[英]JavaScript Object.assign not working on Date object

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: 但是,Date类型的变量似乎不适用于Object.assign和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 我知道我可以使用另一种方式创建Date对象的克隆

b = new Date(a)

But why are Object.assign and Object.create not working on Date type? 但是,为什么Object.assign和Object.create在Date类型上不起作用?

The Object.assign() method copies over the enumerable and own properties of the source object. Object.assign()方法复制源对象的可枚举自己的属性。 A Date instance doesn't really have any of those (if you don't add any with your own code). Date实例实际上没有任何实例(如果您未使用自己的代码添加实例)。

In particular, Date "properties" like the year, month, date, etc. aren't properties in the JavaScript sense. 特别是,日期“属性”(例如年,月,日等)不是JavaScript的属性。 They're values that can be retrieved via the API. 它们是可以通过API检索的值。 That doesn't make them properties. 那不会使它们成为属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM