Extending and inheriting objects
A major advantage of using objects is the capability to reuse already written code in a new context. JavaScript provides a means to modify objects to include new methods and/or properties or even to create brand-new objects based on ones that already exist.
These techniques are known, respectively, as extending
and inheriting
objects.
Extending Objects
What if you want to extend your objects with new methods and properties after the objects have already been instantiated? You can do so using the keyword prototype. The prototype object allows you to quickly add a property or method that is then available for all instances of the object.
Try it Yourself: Extend an Object Using prototype
Let’s extend the Person object of the previous example with a new method, sayHello:
Person.prototype.sayHello = function() { alert(this.name + " says hello"); }c
Create a new HTML file in your editor, and enter the code
Adding a New Method with prototype
<!DOCTYPE html> <html> <head> <title>Object Oriented Programming</title> <script> function Person(personName){ this.name = personName; this.info = 'This person is called ' + this.name; this.showInfo = function(){ alert(this.info); } } var person1 = new Person('Adam'); var person2 = new Person('Eve'); Person.prototype.sayHello = function() { alert(this.name + " says hello"); } </script> </head> <body> <input type="button" value="Show Info on Adam" onclick="person1.showInfo()" /> <input type="button" value="Show Info on Eve" onclick="person2.showInfo()" /> <input type="button" value="Say Hello Adam" onclick="person1.sayHello()" /> <input type="button" value="Say Hello Eve" onclick="person2.sayHello()" /> </body> </html>
Let’s walk through this code and see what’s happening
First, you define a constructor function that takes a single argument, personName. Within the constructor, two properties, name and info, and one method, showInfo, are defined.
You create two objects, instantiating each with a different name property. Having created these two person objects, you then decide to add a further method, sayHello, to the person object definition. You do so using the prototype keyword.
Load the HTML file into your browser. Clicking on the four buttons visible on the page shows that the initially defined showInfo method is still intact, but the new sayHello method operates too, and is available for both of the existing instances of the object type.
Inheritance
Inheritance is the capability to create one object type from another; the new object type inherits the properties and methods of the old, as well as optionally having further properties and methods of its own. This can save you a lot of work, as you can first devise “generic” classes of objects and then refine them into more specific classes by inheritance.
JavaScript uses the prototype keyword to emulate inheritance, too.
Because object.prototype is used to add new methods and properties, you can utilize it to add ALL of the methods and properties of an existing constructor function to your new object.
Let’s define another simple object:
function Pet() { this.animal = ""; this.name = ""; this.setAnimal = function(newAnimal) { this.animal = newAnimal; } this.setName = function(newName) { this.name = newName; } }
A Pet object has properties that contain the type of animal and the name of the pet, and methods to set these values:
var myCat = new Pet(); myCat.setAnimal = "cat"; myCat.setName = "Sylvester";
Now suppose you want to create an object specifically for dogs. Rather than starting from scratch, you want to inherit the Dog object from Pet, but add an additional property, breed, and an additional method, setBreed.
First, let’s create the Dog constructor function and in it define the new property and method:
function Dog() { this.breed = ""; this.setBreed = function(newBreed) { this.breed = newBreed; } }
Having added the new property, breed, and the new method, setBreed, you can now additionally inherit all the properties and methods of Pet. You do so using the prototype keyword:
Dog.prototype = new Pet();
You can now access the properties and methods of Pet in addition to those of Dog:
var myDog = new Dog(); myDog.setName("Alan"); myDog.setBreed("Greyhound"); alert(myDog.name + " is a " + myDog.breed);
Try it Yourself: Extending JavaScript’s Own Objects
Prototype can also be used to extend JavaScript’s built-in objects. You can implement the String.prototype.backwards method, for instance, that will return a reversed version of any string you supply
Extending the String Object
<!DOCTYPE html> <html> <head> <title>Object Oriented Programming</title> <script> String.prototype.backwards = function(){ var out = ''; for(var i = this.length-1; i >= 0; i--){ out += this.substr(i, 1); } return out; } </script> </head> <body> <script> var inString = prompt("Enter your test string:"); document.write(inString.backwards()); </script> </body>
Save the code of given above as an HTML file and open it in your browser. The script uses a prompt() dialog to invite you to enter a string, and then shows the string reversed on the page.
Let’s see how the code works.
String.prototype.backwards = function(){ var out = ''; for(var i = this.length-1; i >= 0; i--){ out += this.substr(i, 1); } return out; }
First, you declare a new variable, out, within the anonymous function that you are creating. This variable will hold the reversed string.
You then begin a loop, starting at the end of the input string (remember that JavaScript string character indexing starts at 0, not 1, so you need to begin at this.length - 1) and decrementing one character at a time. As you loop backwards through the string, you add characters one at a time to your output string stored in out.
When you reach the beginning of the input string, the reversed string is returned. The result is shown as in this