Object-oriented JavaScript
by Greg Brown
|
Pages: 1, 2, 3
Inheritance
Inheritance in object-oriented programming allows developers to define an "is a" relationship between classes. For example, we might want to extend our object model to define slightly more specialized versions of the Pet class: Dog and Cat. The base class, Pet, will contain any properties or methods shared by all Pets, but Dog and Cat may define additional properties or methods applicable only to instances of those classes. For example, our Dog class will provide a wag tail method, and the Cat class will provide a purr method.
In C#:
// C# Dog class
public class Dog : Pet
{
public Dog(string name) : base(name)
{
}
public void WagTail()
{
// Wagging
}
}
// C# Cat class
public class Cat : Pet
{
public Cat(string name) : base(name)
{
}
public void Purr()
{
// Purring
}
}
In JavaScript:
// JavaScript Dog class
function Dog(name) {
Pet.call(this, name);
}
Dog.prototype = new Pet();
Dog.prototype.wagTail = function() {
// Wagging
}
// JavaScript Cat class
function Cat(name) {
Pet.call(this, name);
}
Cat.prototype = new Pet();
Cat.prototype.purr = function() {
// Purring
}
Comparison:
-
In C#, the syntax for declaring a class hierarchy is as follows:
-
public class Dog : PetThis declares the
Dogclass as a subclass ofPet. In JavaScript, the syntax is:Dog.prototype = new Pet();This defines the
Petclass as the prototype object for allDoginstances. Note that a class's constructor function must always be defined before assigning the class's parent prototype, as shown above. -
In C#, the
DogandCatclasses pass the name constructor argument to the base class using the following syntax:public Dog(string name) : base(name) { // ...In JavaScript, the syntax is:
Pet.call(this, name);call()is a built-in JavaScript function that is used to invoke a specific target function in the context of a specific object. In this case, we are invoking thePetconstructor function in the context of theCatorDoginstance. In other words, whenPet()is called, the implicit JavaScript variable will refer to the instance ofCatorDogthat is being constructed.
We can use our new classes and methods as follows. (The only major difference is the declaration of the object types: in C#, Dog and Cat, and in JavaScript, var):
C#:
Dog d = new Dog("Max");
d.WagTail();
Cat c = new Cat("Fluffy");
c.Purr();
JavaScript:
var d = new Dog("Max");
d.wagTail();
var c = new Cat("Fluffy");
c.purr();
This program wouldn't generate any output. However, if we call the GetName()/getName() function from our earlier example, applying it to our Dog instance...
C#:
System.Console.WriteLine(d.GetName());
JavaScript:
alert(d.getName());
...the output is the same as when the method was called on the original Pet instance (see Figure 2):

Figure 2. The output is the same alert.