Introduction:
By now you should have read my tutorial on javascript objects and be able to create and manipulate objects. This is not that complicated if you already understand javascript objects and should be very easy to learn.
The Reasoning:
As objects shorten code, so does inheritance. Inheritance allows multiple objects to share properties/methods of a parent object. In a way javascript objects can have multiple parents, but not in the traditional sense. That is they do not officially have 2 or more parents, but they inherit from 2 or more objects.
Let Us Begin:
Making javascript objects have inheritance is really just a few lines that doesn't take long. Let us start off with our person object:
function Person(name,age) {
this.name = name;
this.age = age;
}
Now, what if we have two types of people that still need to have the properties of the person object? We could do the slow way and define those properties in each object or we could use inheritance. Here is another example assuming the person object is in existence:
function Student(name,age,grade,gpa) {
this.grade = grade;
this.gpa = gpa;
this.parent = Person;
this.parent(name,age);
}
function Employee(name,age,job) {
this.job = job;
this.parent = Person;
this.parent(name,age);
}
That is the way you would do it with inheritance. With so few properties and no methods, it's not that big of a deal, and is in fact more lines just because this example is not that practical. However, with more properties and methods using inheritances the best option.
Multiple Inheritance:
As was said before, objects can have multiple parents through 1 of 2 ways. They can have the equivalent of grandparents by only inheriting one object itself, but since the parent object also inherits the properties/methods of both will be assigned to the grandchild object. The other method is to have multiple parents declared in the object. All you really do is the same method as above, except 2 or more separate times.
Traditional Inheritance:
Multiple inheritance is not technically supported because objects can only have 1 true parent, while they can inherit properties/methods from multiple objects. The reason I use multiple inheritance is because it is a generally close term to what the method of giving an object properties and methods from multiple object. The way to define a traditional parent is like so:
Student.prototype = new Person;
To be honest I have found no use for this as all my objects have arguments.
Summary:
Inheritance can be useful when you have a bunch of properties and methods that need to be shared from various objects. I hope you learned something from this and can find a use for it.
Comments
Post new comment