Hour 6. Understanding and Using JavaScript Objects


What You’ll Learn in This Hour:

Image How to access JavaScript objects

Image Creating and manipulating strings

Image Sorting JavaScript arrays

Image Searching arrays and strings

Image How to create your own custom objects


Much of the code in JavaScript revolves around objects. Objects are a convenient and easy way to group functionality and data together for a variety of purposes. Objects allow you to more easily write code that is clear and easy to implement.

There are four main types of objects that you will be working with in jQuery and JavaScript: DOM, built-in, user-defined, and jQuery. The following sections define object syntax, take you through the most common built-in objects, and show you how to create your own custom objects. DOM objects and jQuery objects are covered in upcoming hours.

Using Object Syntax

To use objects in JavaScript effectively, you need to have an understanding of their structure and syntax. An object is really a container to group multiple values and, in some instances, functions together. The values of an object are called properties, and functions are called methods. Object syntax is very straightforward—you use the object name, then a dot, then the property or method name.

Creating a New Object Instance

To use a JavaScript object, you must first create an instance of the object. Object instances are created using the new keyword with the object constructor name. For example, to create a Number object you use the following line of code:

var x = new Number("5");

Accessing Object Properties

Almost all JavaScript objects have values that are accessible via a standard dot naming syntax. For example, consider an object with the variable name user that contains a property firstName. The following statement accesses the value of the firstName property of the user object:

user.FirstName

Accessing Object Methods

Many JavaScript objects also have methods. An object method is a function that is attached to the object as a name. The function can be called by using the dot syntax to reference the method name. For example, if the object named user had a method called getFullName(), that function can be called by the following statement:

user.getFullName()

Assigning New Values and Methods to Objects

One of the coolest things about objects in JavaScript is that you can assign new property and method values to them at any point using the dot syntax. It doesn’t matter if it is a built-in object or one of your own custom objects. That value can then be accessed later using the same dot syntax.

The following is an example of adding a method and property to the main document object that we have been using for several examples. Notice that we define a simple function that writes the document.me property to the browser. Then we assign a value to document.me and the function writeMe() without the () as document.writeMe. At that point we can call document.writeMe and access the property document.me:

<script>
  function writeMe(){
    document.write(document.me);
  }
  document.me = "Brad Dayley";
  document.writeMe = writeMe;
  document.writeMe();
</script>


Caution

If you assign a new value to an object, the existing properties or methods with the same name will be overwritten. When assigning values to objects, be careful that you do not accidentally overwrite an existing property or method.


Understanding Built-In Objects

JavaScript has several built-in objects that provide a specific set of functionality. Using these built-in objects will save time because they provide already coded and tested methods to handle data. The following sections don’t include all the JavaScript objects, but cover the ones that you need for this book.

Number

The Number object provides functionality that is useful when dealing with numbers. Creating a number object is different from just assigning a number to a variable. When you create a Number object, you also get a set of methods that can be used with it.

The Number object provides the methods listed in Table 6.1. Follow the output results for each of these methods in Table 6.1 based on the following object creation:

var x = new Number("5.55555555");

Image

TABLE 6.1 Using the Built-in Number Object Methods

I chose to pass the number 5.555555555 in as a string instead of a number to illustrate that Number() can accept a string, number, or variable representing a string or a number. The string must be a number string or the value of the Number objects will be NaN (not a number).

It is a good idea to test values before creating the Number object. To test a value and determine whether it is a number, use the isNaN() function. isNaN() returns false if the value is a number or a string that can be a number.


Note

You can use a hexadecimal string when checking for numbers. This is very useful if you are working with hex color values, such as #e0ffff. The string format to use in JavaScript is "0xe0ffff".


String

The String object is by far the most commonly used in JavaScript. JavaScript automatically creates a String object anytime you define a variable that has a string data type. For example:

var myStr = "Teach Yourself jQuery & JavaScript in 24 Hours";

When you create a string, several special characters can’t be directly added to the string. For these characters, JavaScript provides a set of escape codes described in Table 6.2.

Image

TABLE 6.2 Escape Codes Used in JavaScript Strings

To get the length of the string, you can use the length property of the string object, for example:

var numOfChars = myStr.length;

The String object has several functions that allow you to access and manipulate the string in various ways. The methods for string manipulation are described in Table 6.3.

Image
Image

TABLE 6.3 String Object Methods Used to Manipulate JavaScript Strings

To get you started on using the functionality provided in the String object, the following sections describe some of the common tasks that can be done using String object methods.

Combining Strings

Multiple strings can be combined either by using a + operation or by using the concat() function on the first string. For example, in the following code, sentence1 and sentence2 will be the same:

var word1 = "Today ";
var word2 = "is ";
var word3 = "tomorrows' ";
var word4 = "yesterday.";
var sentence1 = word1 + word2 + word3 + word4;
var sentence2 = word1.concat(word2, word3, word4);

Searching a String for a Substring

To tell if a string is a substring of another, you can use the indexOf() method. For example, the following code writes the string to the browser only if it contains the word “think":

var myStr = "I think, therefore I am.";
if (myStr.indexOf("think") != -1){
  document.write(myStr);
}

Replacing a Word in a String

Another common String object task is replacing one substring with another. To replace a word/phrase in a string, use the replace() method. The following code replaces the text "<username>" with the value of the variable username:

var username = "Brad";
var output = "<username> please enter your password: ";
output = output.replace("<username>", username);

Splitting Strings into an Array

A common task with strings is to split them into arrays using a separator character. For example, the following code splits a time string into an array of its basic parts using the split() method on the ":" separator:

var t = "12:10:36";
var tArr = t.split(":");
var hour = tArr[0];
var minute = tArr[1];
var second = tArr[2];

Array

The Array object provides a means of storing and handling a set of other objects. Arrays can store numbers, strings, or other JavaScript objects. You can use a couple of methods to create JavaScript Arrays; for example, the following statements create three identical versions of the same array:

var arr = ["one", "two", "three"];
var arr2 = new Array();
arr2[0] = "one";
arr2[1] = "two";
arr3[2] = "three";
var arr3 = new Array();
arr3.push("one");
arr3.push("two");
arr3.push("three");

To get the number of elements in the array, you can use the length property of the Array object. For example:

var numOfItems = arr.length;

Arrays are a zero-based index, meaning that the first item is at index 0, and so on. You can access the array backward by subtracting using the length attribute. For example, in the following code, the value of variable first will be Monday and the value of variable last will be Friday:

var week = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"];
var first = week[0];
var last = week[week.length-1];

The Array object has several built-in functions that allow you to access and manipulate the array in various ways. Table 6.4 describes the method attached to the Array object that enables you to manipulate the array contents.

Image

TABLE 6.4 Array Object Methods Used to Manipulate JavaScript Arrays

To get you started on using the functionality provided in the Array object, the following sections describe some of the common tasks that can be done using Array object methods.

Combining Arrays

You can combine arrays the same way that you combine String objects, using + statements or using the concat() method. In the following code, arr3 ends up being the same as arr4:

var arr1 = [1,2,3];
var arr2 = ["three", "four", "five"]
var arr3 = arr1 + arr2;
var arr4 = arr1.concat(arr2);


Tip

You can combine an array of numbers and an array of strings. Each item in the array will keep its own object type. However, as you use the items in the array, you need to keep track of arrays that have more than one data type so that you do not run into problems.


Iterating Through Arrays

You can iterate through an array using a for or a for/in loop. The following code illustrates iterating through each item in the array using each method:

var week = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"];
for (var i=0; i<week.length; i++){
  document.write("<li>" + week[i] + "</li>");
}
for (dayIndex in week){
  document.write("<li>" + week[dayIndex] + "</li>");
}

Converting an Array into a String

A useful feature of Array objects is the capability to combine the elements of a string to make a string object separated by a specific separator using the join() method. For example, the following code results in the time components being joined together into the format 12:10:36:

var timeArr = [12,10,36];
var timeStr = timeArr.join(":");

Checking to See Whether an Array Contains an Item

Often, you will need to check to see whether an array contains a certain item. You can do this by using the indexOf() method. If the item is not found in the list, a −1 will be returned. The following function writes a message to the browser if an item is in the week array:

function message(day){
  var week = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"];
  if (week.indexOf(day) != -1){
    document.write("Happy " + day);
  }
}

Adding Items to and Removing Items from Arrays

You can use several methods to add items or remove them from Array objects using the various built-in methods. Table 6.5 gives you some ideas on the various methods used in this book.

Image

TABLE 6.5 Array Object Methods Used to Add or Remove Elements from Arrays

Date

The Date object provides access to the current time on the browser’s system. This can be useful in a lot of ways, such as displaying time on the page, comparing time with the server via AJAX, timing certain events, and the like.

To get the current time on the system, use the following syntax:

var cDate = new Date();
document.write(cDate);

The string version of the date will be similar to the following:

Mon Dec 10 2012 17:30:27 GMT-0700 (Mountain Standard Time)

You can create a Date object using a string or a set of values based on the following syntax:

Date(year, month, day, hours, minutes, seconds, milliseconds)

For example, the following will create the same Date object:

var d1 = Date("2012, 12, 12, 12, 12, 12, 00");
var d2 = Date("December 12, 2012 12:12:12");

JavaScript enables you to compare dates using the normal logical comparisons (<, >, ==, and so on). For example, you could use the following code to compare the current time on the browser with what has been sent from the server as a timestamp: "December 12, 2012 12:12:12".

var currentTime = new Date();
var serverTime = new Date("December 12, 2012 12:12:12");
if (currentTime>serverTime){
    alert("Mayans Wrong?");
}

Math

The Math object is really an interface to a mathematical library that provides a ton of time-saving functionality. The math library is much too large to go over in this book, but Table 6.6 introduces you to some of the more useful functions.

Image

TABLE 6.6 Using the Math Object in JavaScript

RegExp

When dynamically processing user input or even data coming back from the web server, an important tool is regular expressions. Regular expressions allow you to quickly match patterns in text and then act on those patterns.

JavaScript enables you to create a RegExp object that can be used to match patterns in strings using the following syntax:

var re = new RegExp(pattern,modifiers);

Or, more simply:

var re =/pattern/modifiers;

The pattern is a standard regular expression pattern, and the modifiers define the scope to apply the expression. Following is a list of the available modifiers in JavaScript:

Image i—Perform matching that is not case sensitive.

Image g—Perform a global match on all instances rather than just the first.

Image m—Perform multiline match rather than stopping on the first LF/CR character.

The following shows an example of using a regular expression with a string replace() function to do a search for “yourself” that is not case sensitive and replace it with "Your Friends".

var myStr = "Teach Yourself jQuery & JavaScript in 24 Hours";
var re = /yourself/i;
var newStr = myStr.replace(re, "Your Friends");

The value of newStr:

Teach Your Friends jQuery & JavaScript in 24 Hours

If you are not familiar with regular expressions, consider doing some research into it. There are some good books on the topic and several resources on the Web.

Creating Custom-Defined Objects

As you have seen so far, using the built-in JavaScript objects has several advantages. As you begin to write code that uses more and more data, you will find that you want to build your own custom objects with specific properties and methods. The following sections take you through the process of building custom JavaScript objects.

Defining JavaScript Objects

JavaScript objects can be defined using a couple of different ways. The simplest is the on-the-fly method, meaning that you create a generic object and then add properties to it as you need it.

For example, to create a user object and assign a first and last name, you use the following code:

var user = new Object();
user.first="Brad";
user.last="Dayley";

You could also accomplish the same effect through a direct assignment using the following syntax where the object is enclosed in {} brackets and the properties are defined using property:value syntax, as shown next:

var user = {'first':'Brad','last':'Dayley'};

These first two options work very well for simple objects that you do not need to reuse later. A better method is to enclose the object inside its own function block. This has the advantage of enabling you to keep all the code pertaining to the object local to the object itself. For example:

function User(first, last){
  this.first = first;
  this.last = last;
}
var user = new User("Brad", "Dayley");

The end result of these methods is essentially the same. You have an object with properties that that can be referenced using dot syntax, as shown next:

document.write(user.first + " " + user.last);

Adding Methods to JavaScript Objects

If there is code specific to a custom object, you want to attach that code as methods to the object itself. There are a couple of ways to do this depending on how the object was created.

The first way is to define a static function and then assign it as a property of the object. Following is an example of assigning a static function when defining objects on-the-fly:

var user = new Object();
user.first="Brad";
user.last="Dayley";
user.getFullName = makeFullName;
var user2 = {'first':'Brad', 'last':'Dayley',
             'getFullName':makeFullName};
function makeFullName(){
  return this.first + " " + this.last;
}
document.write(user.getFullName());

The function makeFullName() combines and returns the first and last properties of the object as a string. Notice that the function accesses the properties using the this keyword. this refers to the current instance of the object. Also notice that the assignment of the makeFullName() to getFullName omits the () parentheses; this sets user.getFullName equal to the function itself instead of the value it returns.

If you created the object using the better enclosed method, the function can be defined inside the object using the following syntax. Notice that getFullName is set to a newly defined function that returns the value in the same way that the static function makeFullName() did.

function User(first, last){
  this.first = first;
  this.last = last;
  this.getFullName = function(){
      return this.first + " " + this.last;
    };
}

Using a Prototyping Object Pattern

An even more advanced method of creating objects is using a prototyping pattern. The prototyping pattern is implemented by defining the functions inside the prototype attribute of the object instead of the object itself. The reason prototyping is better is that the functions defined in the prototype are created only once when the JavaScript is loaded, instead of each time a new object is created.

The following example shows the code necessary to implement the prototyping pattern. Notice that you define the object UserP and then you set UserP.prototype to include the getFullName() function. You can include as many functions in the prototype as you like. Each time a new object is created, those functions will be available.

function UserP(first, last){
  this.first = first;
  this.last = last;
}
UserP.prototype = {
  getFullName: function(){
      return this.first + " " + this.last;
    }
};

Summary

In this hour, we discussed how JavaScript objects provide a way to create much cleaner and more efficient code. You learned how objects support attaching properties and methods to a single variable name.

You also were introduced to several built-in objects such as Array and String. The built-in objects provide properties and methods that provide quick functionality with little code—for example, using the Date object to get the system time, compare times, and create time-based output to the browser.

Finally, you got a chance to create and manipulate your own JavaScript objects with properties and methods. Creating custom objects will help you organize your scripts to be more efficient.

Q&A

Q. What is the difference between built-in, custom, DOM objects and jQuery objects?

A. Only how they are defined. Built-in objects are automatically defined and available as part of the language sometimes; as with arrays or strings, they are automatically instantiated during an assignment statement. DOM objects are also built in to the JavaScript language. You can create an instance of them in JavaScript, but they are also created based on the tags in the HTML file. jQuery objects are defined and created inside the jQuery library. At the low level, they are all just JavaScript objects. Each has properties and methods that can be used to simplify JavaScript tasks.

Q. The new keyword creates a new instance of an object, but how do I get rid of an instance of an object to free up memory and such?

A. JavaScript automatically cleans up memory for you when a variable goes out of scope. To clean up an instance of a JavaScript object, make it go out of scope. For example, if it is part of an array, you can use the pop() function to remove it, or, if you want all of an array of objects to be freed up, set the array variable to null.

Workshop

The workshop consists of a set of questions and answers designed to solidify your understanding of the material covered in this hour. Try to answer the questions before looking at the answers.

Quiz

1. What is the new keyword for?

2. How do you find the length of a JavaScript array?

3. True or False: The following statement creates a copy of the Array object named myArr:

var newArr = myArr.concat([])

4. True or False: You cannot assign new properties to an existing JavaScript object.

Quiz Answers

1. The new keyword is used to create a new instance of an object.

2. The length of JavaScript String and Array objects can be found using the length property. For example:

myArr.length

3. True.

4. False.

Exercises

1. Extend the code in Listing 6.1 to include a much more complete madlib. Add several attributes that should be included in the final string.

2. Use the code in Listing 6.2 as an outline to create and display arrays that contain the summer months, winter months, autumn months, and spring months. Then combine the arrays into a single array containing all the months of the year.

3. Extend Listing 6.3 to add all the members of the “Fellowship of the Rings.” A listing can be found by doing an Internet search. Also include additional attributes such as weapon, age, or height.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset