简体   繁体   English

将自定义字段/键添加到Javascript Date对象

[英]Add a custom field/key to a Javascript Date object

I'm in a situation where the cleanest and least cumbersome way to get the job done is by augmenting the Javascript Date object with an extra field. 我处于一种最干净,最不麻烦的方式来完成工作的情况下,就是通过使用额外的字段来扩展Javascript Date对象。 The extra field will store some meta-data about the origin of that particular date, which is then used by the on-page JS while rendering the UI. extra字段将存储有关该特定日期的起源的一些元数据,然后页面JS在渲染UI时将其使用。

My question is -- is it a good idea to the following: 我的问题是-以下内容是否是个好主意:

d = new Date();
d._my_ns_metadata = "some meta-data comes here";

I tried reading-up on JS monkey-patching, but everyone seems to be talking about changing/adding function definitions to the object's Prototype. 我尝试阅读有关JS猴子补丁的内容,但似乎每个人都在谈论将功能定义更改/添加到对象的Prototype。 Here I'm just adding an individual field/key to a Date object. 在这里,我只是向Date对象添加一个单独的字段/键。

The problem with your approach is that only that instance of Date will get that metadata. 您的方法存在的问题是,只有Date实例才能获取该元数据。 Any other instances will not, unless you have some other function that automatically augments it to the instance. 除非您具有自动将其扩展到实例的其他功能 ,否则其他任何实例都不会。 Something like: 就像是:

function dateWithMetaData(meta){
  var aDate = newDate();
  aDate._my_ns_metadata = meta;
  return aDate;
}

var d = dateWithMetaData("some meta-data comes here");

But then, where would you place that function so that it is immediately accessible anywhere for any instance of Date ? 但是,那您将在哪里放置该函数,以便可以在任何地方为Date任何实例立即访问它? Where else but the Date.prototype of course. 当然还有Date.prototype Adding something to an object's prototype makes it available to all instances of it. 在对象的原型中添加某些内容使其可用于其所有实例。 Thus you can do this: 因此,您可以执行以下操作:

// Modifying the prototype
Date.prototype.setMetaData = function(meta){
  this._my_ns_metadata = meta;
}

// Now any instance of Date has setMetaData
var d = new Date();
d.setMetaData("some meta-data comes here");

var x = new Date();
x.setMetaData("some meta-data comes here");

By design, JS allows modification of native objects. 通过设计,JS允许修改本机对象。 However, it's not really advisable to modify objects you don't own. 但是,不建议您修改您不拥有的对象。 You might unintentionally break stuff. 您可能无意间破坏了东西。

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

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