Training Guide: Programming in HTML5 with JavaScript and CSS3 Ebook

(Nora) #1

Lesson 1: Creating JavaScript objects CHAPTER 6 271


you expected? Is that what you wanted? You can see that in some scenarios, this behavior is
desirable, but in other scenarios, you might have wanted to replace the function across all
objects. To do this, you use the prototype pattern.

NOTE ACCESS TO PRIVATE DATA
In the example, the replacement function cannot access the private data because the
replacement is executed externally to the Vehicle.

FIGURE 6-4 uccessful first assertion, proving that the function was replaced; failed second assertion, S
proving that the second Vehicle’s function was not replaced

Using the prototype property


In JavaScript, everything, including the function, is an Object type, which has a prototype
property. The prototype itself is an object containing properties and methods that should be
available to all instances of the type you’re working with. However, this prototype is typi-
cally specified externally to the constructor function, so the prototype doesn’t have access to
private variables. Therefore, you must expose the data for the prototype to work. The follow-
ing is an example of using the prototype property to create a single getInfo method that is
shared across all instances.
function Vehicle(theYear, theMake, theModel) {
this.year = theYear;
Free download pdf