Chaining Constructors and JS Inheritance
JavaScript is not a typical OO language, and shouldn’t be pushed, pummeled, or constrained into one. It has its own strengths, which should be used to advantage. Still, there are pieces of traditional object-oriented design that would be nice to use in applications. In the last section we saw one type of OO-based design: encapsulation. This section covers another: inheritance.
Inheritance incorporates, or inherits,
another object’s methods and properties in a new object. It’s the
fundamental power of class-oriented development because one class can
inherit from another class, choosing to override whatever functions that
have a new behavior in the new class. Something similar can be used in
JS to emulate this behavior, starting with JavaScript 1.3—the function
methods of apply and call.
Returning to previous examples, when a function defining a new
object is written, it becomes the object constructor and is invoked when
the new keyword is used with the
function:
theobj = new DivObj(params);
Both the function apply and
call methods allow you to apply or invoke a method within the context of another object. If used with an object constructor, it chains the constructors in such a way that all properties and methods of the one object are inherited by the containing object. The only difference between the two is the parameters passed; the behavior is the same. The call method takes the containing object as the first parameter, identified using ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access