Sign In Start Free Trial
Account

Add to playlist

Create a Playlist

Modal Close icon
You need to login to use this feature.
  • Book Overview & Buying Object-Oriented JavaScript
  • Table Of Contents Toc
Object-Oriented JavaScript

Object-Oriented JavaScript

4.5 (48)
close
close
Object-Oriented JavaScript

Object-Oriented JavaScript

4.5 (48)

Overview of this book

Table of Contents (18 chapters)
close
close
Object-Oriented JavaScript
Credits
About the Author
About the Reviewers
Preface
2
Built-in Functions
4
Regular Expressions
5
Index

Parasitic Inheritance


I f you like the fact that you can have all kinds of different ways to implement inheritance in JavaScript, and you're hungry for more, here's another one. This pattern, courtesy of Douglas Crockford, is called parasitic inheritance. It basically means that you can have a function that creates objects by taking all of the functionality of another object, augmenting it and returning it, "pretending that it has done all the work".

Here's an ordinary object, defined with an object literal, and unaware of the fact that it is soon going to fall victim to parasitism:

var twoD = {
  name: '2D shape',
  dimensions: 2
};

A function that creates triangle objects could:

  • Clone the twoD object into an object called that. This can be done in any way you saw above, for example using the object() function or copying all the properties.

  • Augment that with more properties.

  • Return that.

function triangle(s, h) {
  var that = object(twoD);
  that.name ='Triangle';
  that.getArea = function(...
CONTINUE READING
83
Tech Concepts
36
Programming languages
73
Tech Tools
Icon Unlimited access to the largest independent learning library in tech of over 8,000 expert-authored tech books and videos.
Icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Icon 50+ new titles added per month and exclusive early access to books as they are being written.
Object-Oriented JavaScript
notes
bookmark Notes and Bookmarks search Search in title playlist Add to playlist font-size Font size

Change the font size

margin-width Margin width

Change margin width

day-mode Day/Sepia/Night Modes

Change background colour

Close icon Search
Country selected

Close icon Your notes and bookmarks

Confirmation

Modal Close icon
claim successful

Buy this book with your credits?

Modal Close icon
Are you sure you want to buy this book with one of your credits?
Close
YES, BUY

Submit Your Feedback

Modal Close icon
Modal Close icon
Modal Close icon