In this chapter, you learned quite a few ways (patterns) of implementing inheritance, and the following table summarizes them. The different types can roughly be divided into the following:
You can also classify the patterns based on whether they:
# |
Name |
Example |
Classification |
Notes |
---|---|---|---|---|
1 |
Prototype chaining
(pseudo-classical)
|
Child.prototype = new Parent();
|
|
|
2 |
Inherit only the prototype |
Child.prototype = Parent.prototype;
|
|
|
3 |
Temporary constructor |
function extend(Child, Parent) { var F = function(){}; F.prototype = Parent.prototype; Child.prototype = new F(); Child.prototype.constructor = Child; Child.uber = Parent.prototype; }
|
|
|
4 |
Copying the |
function extend2(Child, Parent) { var p = Parent.prototype; var c = Child.prototype; for (var i in p) { c[i] = p[i]; } c.uber = p; }
|
|
|
5 |
Copy all properties
(shallow copy)
|
function extendCopy(p) { var c = {}; for (var i in p) { c[i] = p[i]; } c.uber = p; return c; }
|
|
|
6 |
Deep copy |
Same as the previous one, but recurse into objects |
|
|
7 |
Prototypal inheritance |
function object(o){ function F() {} F.prototype = o; return new F(); }
|
|
|
8 |
Extend and augment |
function objectPlus(o, stuff) { var n; function F() {} F.prototype = o; n = new F(); n.uber = o; for (var i in stuff) { n[i] = stuff[i]; } return n; }
|
|
|
9 |
Multiple inheritance |
function multi() { var n = {}, stuff, j = 0, len = arguments.length; for (j = 0; j <len; j++) { stuff = arguments[j]; for (var i in stuff) { n[i] = stuff[i]; } } return n; }
|
|
|
10 |
Parasitic inheritance |
function parasite(victim) { var that = object(victim); that.more = 1; return that; }
|
|
|
11 |
Borrowing constructors |
function Child() { Parent.apply(this, arguments); }
|
|
|
12 |
Borrow a constructor and copy the prototype |
function Child() { Parent.apply(this, arguments); } extend2(Child, Parent);
|
|
|
Given so many options, you must be wondering which is the right one. That depends on your style and preferences, your project, task, and team. Are you more comfortable thinking in terms of classes? Then pick one of the methods that work with constructors. Are you going to need just one or a few instances of your class? Then choose an object-based pattern.
Are these the only ways of implementing inheritance? No. You can choose a pattern from the preceding table, you can mix them, or you can think of your own. The important thing is to understand and be comfortable with objects, prototypes, and constructors; the rest is just pure joy.
18.225.35.81