0

I added this code:

Date.prototype.formatMMDDYYYY = function () {
  return (this.getMonth() + 1) +
    "/" + this.getDate() +
    "/" + this.getFullYear();
}

Resharper's code inspection tool tells me that Extending prototype of native object 'Date' may cause unexpected effects.

What are some of the unexpected effects that might happen?

P.S. This question has a discussion why it's a bad idea to extend objects in general, but all the answers are very vague. I am looking for a specific side effect of me extending the Date object in the manner that I did.

AngryHacker
  • 59,598
  • 102
  • 325
  • 594
  • 1
    @Ivar I clarified the question. Basically I am looking for specifics which the question you linked to doesn't provide. – AngryHacker Oct 13 '17 at 17:30

1 Answers1

2

That function should work fine. If you were manipulating properties or overriding a function that already existed you could have problems.

For example instead of this.getmonth() + 1 you did this.month++ or whatever the internal is called you have just changed the date and every time the function is called you are changing the date. Obviously overriding a function would change that function in every place that would have your is included. If for some so if you are on a web page and you load 5 script files they would all use the overridden function. And that would likely have unexpected results. Especially if the scripts are unrelated.

All that being said it's probably better to build that as a wrapper FormatDate (date) { return (date.getDate, ...)} As this would prevent future naming collisions and so on. Imagine trying to fix that 5 years from now for example. You could also make a date subclass that does those things and use that if you wanted.

random-parts
  • 2,137
  • 2
  • 13
  • 20
Ken Fitts
  • 36
  • 1