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:
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.
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)));