0

I am trying to pass Date object as a value to Javascript constructor for Mac Automation Scripting. Here is the code that I am trying to run:

app = Application.currentApplication();
app.includeStandardAdditions = true;
app.strictPropertyScope = true;

Date.prototype.month = function () {
  return this.getMonth();
};

class Birthday {
  constructor(name, date) {
    this.name = name;
    this.date = date;
    this.mydate = new Date(2018, 0, 5);
  }
}

var birthdays = [];
birthdays.push(new Birthday('John Doe1'), Date.now(2018, 0, 1));
// birthdays.push(new Birthday("John Doe2"), Date.now(2018, 0, 2));
// birthdays.push(new Birthday("John Doe3"), Date.now(2018, 0, 3));
// continued ...

console.log(birthdays[0].name);   // John Doe1
console.log(birthdays[0].date);   // undefined (*1)
console.log(birthdays[0].month);  // undefined (*2)
console.log(birthdays[0].mydate); // Fri Jan 05 2018 00:00:00 GMT...

Unexpected results:

  1. undefined for the member of Birthday class
  2. undefined for the function that I added to Date.prototype

This code used to work. As you can see, if I instantiate Date inside of constructor, it would work. So, I could change the constructor of Birthday class as follows:

class Birthday {
  constructor(name, year, month, day) {
    this.name = name;
    this.date = new Date(year, month, day);
  }
}

However, I have so many lines of instantiations of Birthday, and I am just curious why this code is not working any more.

Please let me know if you know anything about this matter. Thank you in advance.

ys64
  • 290
  • 2
  • 8

2 Answers2

0

You're passing the result of Date.now() into the constructor. Date.now returns and Number, not a Date object.

You probably want something like:

birthdays.push(new Birthday('John Doe1', new Date(2018, 0, 1)));

instead.

EDIT:

I just noticed a syntax error as well. You're closing your parens too early, so in your code you're never passing the Date.now() result as a constructor parameter, you're passing it as a second parameter to birthdays.push(). You'll want to change:

birthdays.push(new Birthday('John Doe1'), Date.now(2018, 0, 1));

to

birthdays.push(new Birthday('John Doe1', new Date(2018, 0, 1)));
bmceldowney
  • 2,307
  • 13
  • 19
0

along with what bmceldowney said, you’re not passing in a date object and month should be month() when you call it cus it’s a function not a property

mad.meesh
  • 2,558
  • 1
  • 13
  • 20