Back in the dark days before the W3C DOM evolved to its current state, JavaScript developers were forced into horrible code contortions to try to cope with browsers’ different DOM implementations. It was not uncommon for scripts to be written almost as two or more separate programs, the version to be executed only being decided after an attempt to detect the browser in use.
As you saw in your work with the navigator object in Hour 4, “DOM Objects and Built-in Objects,” browser detection is a tricky business. The navigator object contains information that can be misleading at best (and sometimes downright
incorrect). Also, when a new browser or version is introduced with new capabilities and features, your browser-detecting code is usually broken once again.
Thankfully a much better way to write cross-browser code has emerged, based on objects. Instead of attempting browser detection, it’s a much better idea to have
JavaScript examine whether the particular feature you need is supported. You can do this by testing for the availability of a specific object, method, or property. In many cases it’s sufficient to try to use the object, method, or property in question, and detect the value JavaScript returns.
Here’s an example of testing for browser support of the
document.getElementById() method, which you’ve already met. While getElementById() has been supported by all new browsers for some time now, very early browsers do not support this method. You can test for the availability of the getElementById() method (or any similar method or property) by using if():
Click he re to vie w code image
if(document.getElementById) {
myElement = document.getElementById(id); } else {
// do something else }
If document.getElementById is not available, the if() conditional statement will switch code operation to avoid using that method.
Another, related method uses the typeof operator to check whether a JavaScript function exists before calling it:
Click he re to vie w code image
if(typeof document.getElementById == 'function') { // you can use getElementById()
} else {
// do something else }
A number of possible values can be returned by typeof, as listed in Table 8.1.
TABLE 8.1 Values Returned by typeof
You can use this technique to check for the existence not only of DOM and built-in objects, methods, and properties, but also those created within your scripts.
has—you simply want to know whether it supports the objects, properties, or methods you are about to try to use. Not only is such feature detection much more accurate and elegant than so-called browser sniffing (trying to infer the browser in use by
interpreting properties of the navigator object), but it’s also much more future proof —the introduction of new browsers or browser versions won’t break anything in your code’s operation.
Summary
In this hour you learned about object-oriented programming (OOP) in JavaScript, starting with the basic concepts behind OOP, and how it can help your code development, especially for more complex applications.
You learned a way to directly instantiate an object and add properties and methods to it. You then learned to create an object constructor function, from which you can instantiate multiple similar objects.
You also learned about the prototype keyword, and how it can be used to extend objects or create new objects via inheritance.
Q&A
Q. Should I always write object-oriented code?
A. It’s a matter of personal preference. Some coders prefer to always think in terms
of objects, methods, and properties, and write all their code with those principles in mind. Others feel that, particularly for smaller and simpler programs, the level of abstraction provided by OOP is too much, and that procedural coding is OK.
Q. How would I use my objects in other programs?
A. An object’s constructor function is quite a portable entity. If you link into your
page a JavaScript file containing an object constructor function, you have the means to create objects and use their properties and methods throughout your code.
Workshop
Try to answer all the questions before reading the subsequent “Answers” section.
Quiz
1. A new object created from a constructor function is known as: a. an instance of the object
b. a method of the object c. a prototype
2. Deriving new objects by using the design of currently existing objects is known
as:
a. Encapsulation b. Inheritance c. Instantiation
3. Which of the following is a valid way to create a direct instance of an object? a. myObject.create();
b. myObject = new Object; c. myObject = new Object();
Answers
1. a. A new object created from a constructor function is known as an instance.
2. b. New objects are derived from existing ones through inheritance.
3. c. myObject = new Object();
Exercises
Write a constructor function for a Card object with properties of suit
(diamonds, hearts, spades, or clubs) and face (ace, 2, 3 ...king). Add methods to set the values of suit and face.
Can you include a shuffle method to set the suit and face properties to represent a random card from the deck? (Hint: Use the Math.random() method described in Hour 4, “DOM Objects and Built-in Objects.”)
Extend JavaScript’s Date object using the prototype keyword to add a new method, getYesterday(), that returns the name of the previous day to that represented by the Date object.
Hour 9. Scripting with the DOM
What You’ll Learn in This Hour:
The concept of nodes
The different types of nodes
Using nodeName, nodeType, and nodeValue Using the childNodes collection
Selecting elements with getElementsByTagName() How to use Mozilla’s DOM Inspector
How to create new elements
Ways to add, edit, and remove child nodes Dynamically loading JavaScript files Changing element attributes
You’ve already learned about the W3C DOM and, in the code examples of previous hours, you used various DOM objects, properties, and methods.
In this hour you begin exploring how JavaScript can directly interact with the DOM. In particular, you learn some new ways to navigate around the DOM, selecting particular DOM objects that represent parts of the page’s HTML contents. You see how to create new elements, how to add, edit, and remove nodes of the DOM tree, and how to
manipulate elements’ attributes.