- It Works Like This
- Preparing to Work
- Using #include to Load ActionScript from a Text File
- Running Conditional Code with OnClipEvent
- The Time Zone Button Layer
- Using Functions to Repeat Common Tasks
- Keeping Time with the ActionScript Date Object
- Using Prototype to Extend the Date Object
- Updating in Real Time
- Updating the Mouse Time Zone
- Setting an Analogue Clock
- Setting a Row of Clocks
- Using setInterval to Update the Clocks
- Summary
- About This Article
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.
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.
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.