Publishers of technology books, eBooks, and videos for creative people

Home > Articles

  • Print
  • + Share This
From the author of

Using Prototype to Extend the Date Object

ActionScript is based on ECMA-262, the same standard used by JavaScript. Consequently, the ActionScript and JavaScript Date objects and methods are almost identical. There are, however, several useful Date methods that, mainly due to localization issues, don't exist in either language. The names of the months and weekdays are a good example. Next you're going to add these new methods to the Date object.

This next function declaration will be slightly different from previous ones. This one makes use of the .prototype method to extend the Date object. In layman's terms, this syntax enables you to add your own function calls to an existing ActionScript object. Once applied, these can be called just as you would any object method.

  1. Insert this code into the function declaration section:

    // FUNCTION: to return the weekday name
    Date.prototype.getUTCDayName = function() {
      var daynames = new Array('Sunday', 'Monday', 'Tuesday',
       'Wednesday', 'Thursday', 'Friday', 'Saturday');
      return daynames[this.getUTCDay()];

    When called, this function returns the name of the weekday. First, the function creates a temporary array called daynames to store the names of all the days of the week. When any variable is preceded with the var statement, it is deemed to be local and only exists for the duration of the function. The return line for this function takes the Date's existing .getUTCDay() method and uses it to access the correct day within the daynames array.

  2. Insert this code into the function declaration section:

    // FUNCTION: to return the month name
    Date.prototype.getUTCMonthName = function() {
      var monthnames = new Array('January', 'February', 'March', 
    'April', 'May', 'June', 'July', 'August',
     'September', 'October', 'November', 'December');
       return monthnames[this.getUTCMonth()];

    This last function uses a similar array lookup technique to return the name of the month. When you understand the syntax of these extensions, you'll find them very easy to write. They are also very simple to translate into other languages.

  • + Share This
  • 🔖 Save To Your Account