1

I've been struggling with the loosely-typed nature of JavaScript lately. I've been writing a program that makes API calls to fetch data, and stores the resulting data in a custom class. One of the values of the custom class is a date, which is supposed to be of the Date type. Before creating the object, I always convert the date value to a proper Date object before passing it into the constructor.

For reference, this is what the class looks like:

class Item {
    constructor(title, date) {
      this.title = title;
      this.date = date;
    }
}

However, when I attempt to retrieve the date value and compare it to another date value later on, it seems to have reverted to a normal object type, as the console claims item.date.compare isn't a function. Logging has indicated the type of the object is a generic object, but that it's an instance of Date. But I haven't been able to figure out how to treat it as specifically a Date object.

As of now I've tried casting, which hasn't worked. Namely, I've tried doing item.date as Date as well as Object.create(Date, item.date). Neither has worked so far. What am I missing?

AtheistP3ace
  • 9,611
  • 12
  • 43
  • 43
Technicolor
  • 1,589
  • 2
  • 17
  • 31
  • 1
    Without seeing the code involved in handling the values, it's hard to say. – Pointy Jun 22 '17 at 13:28
  • You need to show us a minimal working version of your code. Also, you are making an "instance" of `Item`, right? – Scott Marcus Jun 22 '17 at 13:28
  • Something is changing the variable, it's that simple. Any time you use the variable, make sure you console.log the value and type of it. Also, what they said - more code, or we can't help other than vague suggestions. – Sean Kendle Jun 22 '17 at 13:32
  • Be careful of global scope. If you're declaring the variable inside a function with `var`, it's scoped to that function. If you didn't use `var` it's a global object. – Sean Kendle Jun 22 '17 at 13:33

1 Answers1

3

As long as you are instantiating your class properly and passing the correct data, you'll have a date.

The reason you are getting your error is simple, The JavaScript Date type doesn't have a compare method.

See this for how to compare dates.

class Item {
    constructor(title, date) {
      this.title = title;
      this.date = date;
    }
}

var myItem = new Item("test instance", new Date());

console.log(myItem.date.constructor, myItem.date);
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71