HTML and CSS Reference
In-Depth Information
The second parameter enables you to add properties or behaviors to the object being
created. Essentially, you define this additional prototype information inline with the object
creation. This example adds the property hasSound, which has a default value specified as
false . You could also specify additional information here, such as whether the property is
read-only and whether it's enumerable. Creating objects this way is similar to the inline ex-
ample in the beginning of the earlier section on custom objects. Again, such an approach isn't
very modular or reusable. For every instance of a pop-up book, you'd need to declare the
additional property and method. So again, for objects that you might want to reuse often,
extending the Book prototype is better.
Extending the Book prototype is much the same as creating a new prototype. You need
only one line of code to tell JavaScript to inherit the functionality and attributes of another
object. You do this by initializing the prototype to the parent object:
function PopUpBook() {;
PopUpBook.prototype = Book.prototype;
PopUpBook.prototype.hasSound = false;
PopUpBook.prototype.showPopUp = function ShowPop() { };
In this way, PopUpBook now extends the implementation of the Book object and adds its
own functionality for reuse. The function PopUpBook makes a method call to . This
is a call to the constructor of the super class (the class being inherited from). If the super class
has a constructor that takes parameters, this method would enable you to pass the parameter
values to the super-class constructors for object initialization.
Thought experiment
Creating synergy between custom objects and native objects
In this thought experiment, apply what you've learned about this objective. You can
find answers to these questions in the “Answers” section at the end of this chapter.
In this objective you've seen the use of native objects and custom objects. How
would you bring those two worlds together? In JavaScript, inheriting from native
objects is not fully supported. However, what if you wanted to add functionality to
native objects by extending them? How would you go about doing this?
Search WWH ::

Custom Search