Question

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

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. Here I'm just adding an individual field/key to a Date object.

No correct solution

OTHER TIPS

The problem with your approach is that only that instance of Date will get that metadata. 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? Where else but the Date.prototype of course. 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. However, it's not really advisable to modify objects you don't own. You might unintentionally break stuff.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top