Objects

JavaScript is an object-based language and as such, many of its components are themselves objects . Some of the native objects in JavaScript we’ve already discussed: Array and Function. Some others are Element, Math, and Date. You can also create custom objects, which we’ll get to in a moment.

An object is essentially a self-contained collection of data. There are two data types available to it: properties and methods. Properties are values, while methods are functions. What makes objects useful is that they share access to their properties and methods.

Let’s look at two examples of the built-in JavaScript objects in action:

    var num = 1.76543;
        num = Math.round(num); // 2
    var now  = new Date( );
    var days = [ 'Sunday', 'Monday', 'Tuesday', 'Wednesday',
                 'Thursday', 'Friday', 'Saturday'];
    var day  = days[ now.getDay( ) ];
    alert( 'Today is ' + day );

In the first example, we used a method of the Math object to round our variable up. In the second example, we created a new instance of the Date object and then used its getDay( ) method to tell us what today is by selecting the day name from an array of day names (the getDay( ) method returns the index number of the weekday, 0 through 6 starting with Sunday, which is why that worked). Table 26-4 has a listing of a few native JavaScript objects and their most commonly used properties and methods.

Get Web Design in a Nutshell, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.