-2

I have a problem with this code in google chrome and firefox. this.setUTCDate(1); throws Uncaught TypeError: this is not a Date object. How can I fix it?

I've looked at this and this, but I didn't find anything to solve my problem.

Date.prototype.setUTCDateOnly = function(date) {
    var tmp = new Date(date);
    this.setUTCDate(1);
};

I am calling it in this way:

var date = Date.prototype.setUTCDateOnly(item.date);
Community
  • 1
  • 1
Pooya
  • 4,385
  • 6
  • 45
  • 73

2 Answers2

3

Methods added to the .prototype of a constructor are meant to operate on instances created from that constructor. Instead, you're operating on the .prototype object itself.

Why? Because the value of this in your case is set by looking to the left hand side of the . operator. In other words, the object on which the method is called becomes the value of this in the method.

That's not the only way this can be set, but it is the default, implicit behavior when invoking methods.

So what you need to do is create a Date object like you normally would, then call your method on that object to have it operate on that object.

var mydate = new Date();
mydate.setUTCDateOnly(item.date);
2

Since you call your method like this

Date.prototype.setUTCDateOnly(item.date);

then the this value will be Date.prototype.

In ES5, Date.prototype was a Date object:

The Date prototype object is itself a Date object (its [[Class]] is "Date") whose [[PrimitiveValue]] is NaN.

Therefore, you could call setUTCDate on it. The NaN was just transformed into a +0 by ToInteger inside MakeDay.

However, this changed in ES6, now Date.prototype is defined as

The Date prototype object is itself an ordinary object. It is not a Date instance and does not have a [[DateValue]] internal slot.

Therefore, attempting to call setUTCDate on it throws.

Oriol
  • 274,082
  • 63
  • 437
  • 513
  • Thanks, Because I didn't know that the new google chrome changed the ECMA script engine to 6 – Pooya Dec 31 '15 at 16:14
  • @Пуя It's more like a gradual transition. New browser versions are becoming closer to the ES6 spec. – Oriol Dec 31 '15 at 16:17