Please note, this is a STATIC archive of website developer.mozilla.org from 03 Nov 2016, cach3.com does not collect or store any user information, there is no "phishing" involved.

Revision 1116519 of Inheritance in JavaScript

  • Revision slug: Learn/JavaScript/Objects/Inheritance
  • Revision title: Inheritance in JavaScript
  • Revision id: 1116519
  • Created:
  • Creator: chrisdavidmills
  • Is current revision? No
  • Comment

Revision Content

{{draft}}{{LearnSidebar}}
{{PreviousMenuNext("Learn/JavaScript/Objects/Object_prototypes", "Learn/JavaScript/Objects/Build_your_own", "Learn/JavaScript/Objects")}}

With most of the gory details of OOJS now explained, this article shows how to create "child" object classes (constructors) that inherit features from their "parent" classes. In addition, we present some advice on when and where you might use OOJS.

Prerequisites: Basic computer literacy, a basic understanding of HTML and CSS, familiarity with JavaScript basics (see First steps and Building blocks) and OOJS basics (see Introduction to objects).
Objective: To understand how it is possible to implement inheritance in JavaScript.

Prototypal inheritance??

So far we have seen some inheritance in action — we have seen how prototype chains work, and how members are inherited going up a chain. But mostly this has involved built-in browser functions. How do we create an object in JavaScript that inherits from another object?

Well, as mentioned before JavaScript is not a true object-oriented language. In such languages, you tend to define class objects of some kind, and you can then simply define which classes inherit from which other classes (see C++ inheritance for some simple examples). In JavaScript it is not quite that simple — it is possible to create a system something this, but it is regarded as somewhat of a hack. And you must remember that such "inheriting" objects are not undergoing true inheritance (with functionality being copied over). Instead, the functionality they inherit is linked to via the prototype chain (often referred to as prototypal inheritance).

Let's explore how to do this with a concrete example.

Getting started

First of all, make youself a local copy of our oojs-class-inheritance-start.html file (see it running live also). Inside here you'll find the same Person() constructor example that we've been using all the way through the module, with a slightly difference — we've defined only the properties inside the constructor:

function Person(first, last, age, gender, interests) {
  this.name = {
    first,
    last
  };
  this.age = age;
  this.gender = gender;
  this.interests = interests;
};

The methods are all defined on the constructor's prototype, for example:

Person.prototype.greeting = function() {
  alert('Hi! I\'m ' + this.name.first + '.');
};

So, say we wanted to create a Teacher class, like the one we described in our initial object-oriented definition, which inherits all the members from Person, but also includes:

  1. A new property, subject — this will contain the subject the teacher teaches.
  2. An updated greeting() method, which sounds a bit more formal than the standard greeting() method — more suitable for a teacher addressing some students at school.

Defining a Teacher() constructor function

The first thing we need to do is create a Teacher() constructor — add the following below the existing code:

function Teacher(first, last, age, gender, interests, subject) {
  Person.call(this, first, last, age, gender, interests);

  this.subject = subject;
}

This looks similar to the Person constructor in many ways, but there is something strange here that we've not seen before — the call() function. This function basically allows you to call a function defined somewhere else in the current context. The first parameter specifies the value of this that you want to use when running the function, and the other parameters specify the parameters that the function should have passed to it when it runs.

So in this case we are effectively running the Person() constructor function (see above) inside the Teacher() constructor function, resulting in the same properties being defined inside Teacher(), using the values of the parameters passed to Teacher(), not Person() (we are using simply this as the value of this passed to call(), meaning that this will be the Teacher() function).

The last line inside the constructor simply defines the new subject property that teachers are going to have, which generic people won't have.

As a note, we could have simply done this:

function Teacher(first, last, age, gender, interests, subject) {
  this.name = {
    first,
    last
  };
  this.age = age;
  this.gender = gender;
  this.interests = interests;
  this.subject = subject;
}

But this is just redefining the properties anew, not inheriting them from Person(), so it defeats the point of what we are trying to do. It also takes more lines of code.

Setting Teacher()'s prototype and constructor reference

All is good so far, but we have a problem. We have defined a new constructor, and it has an empty prototype property by default. We need to get Teacher() to inherit the methods defined on Person()'s prototype. So how do we do that?

  1. Add the following line below your previous addition:
    Teacher.prototype = Object.create(Person.prototype);
    Here our friend create() comes to the rescue again — in this case we are using it to create a new prototype property value (which is itself an object that contains properties and methods) with a prototype equal to Person.protype, and set that to be the value of Teacher.prototype. This means that Teacher.prototype will now inherit all the methods available on Person.prototype.
  2. We need to do one more thing before we move on — the Teacher() prototype's constructor property is currently set as Person(), because of the way we inherited from it (this Stack Overflow post has more information on why) — try saving your code, loading the page in a browser, and entering this into the JavaScript console to verify:
    Teacher.prototype.constructor
  3. This can become a problem, so we need to set this right — you can do so by going back to your source code and adding the following line at the bottom:
    Teacher.prototype.constructor = Teacher;
  4. Now if you save and refresh, entering Teacher.prototype.constructor should return Teacher(), as desired.

Giving Teacher() a new greeting() function

To finish off our code, we need to define a new greeting() function on the Teacher() constructor.

The easiest way to do this is to define it on Teacher()'s prototype — add the following at the bottom of your code:

Teacher.prototype.greeting = function() {
  var prefix;

  if(this.gender === 'male' || this.gender === 'Male' || this.gender === 'm' || this.gender === 'M') {
    prefix = 'Mr.';
  } else if(this.gender === 'female' || this.gender === 'Female' || this.gender === 'f' || this.gender === 'F') {
    prefix = 'Mrs.';
  } else {
    prefix = 'Mx.';
  }

  alert('Hello. My name is ' + prefix + ' ' + this.name.last + ', and I teach ' + this.subject + '.');
};

This alerts the teacher's greeting, which also uses an appropriate name prefix for their gender, worked out using a conditional statement.

Trying the example out

Now you've entered all the code, try creating an object instance from Teacher() by putting the following at the bottom of your JavaScript (or something similar of your choosing):

var teacher1 = new Teacher('Dave', 'Griffiths', 31, 'male', ['football', 'cookery'], 'mathematics');

Now save and refresh, and try accessing the properties and methods of your new teacher1 object, for example:

teacher1.name.first;
teacher1.interests[0];
teacher1.bio();
teacher1.subject;
teacher1.greeting();

These should all work just fine; the first three access members that were inherited from the generic Person() constructor (class), while the last two access members that are only available on the more specialised Teacher() constructor (class).

Note: If you have trouble getting this to work, compare your code to our finished version (see it running live also).

The technique we covered here is a bit convoluted, and it is certainly not the only way to create inheriting classes in JavaScript, but it works ok, and it gives you a good idea about inheritance in JavaScript. You might also be interested in checking out some of the new {{glossary("ECMAScript")}} features that allow us to do inheritance more cleanly in JavaScript (see Classes). We didn't cover those here, as they are not yet supported very widely across browsers. All the other code constructs we discussed in this set of articles are supported as far back as IE9 or earlier, and there are ways to achieve earlier support than that.

A common way is to use a JavaScript library — most of the popular options have an easy set of functionaily available for doing inheritance more easily and quickly. CoffeeScript for example provides class, extends, etc.

A further exercise

In our OOP theory section, we also included a Student class as a concept, which inherits all the features of Person, and also has a different greeting() method to Person that is much more informal than the Teacher's greeting. Have a look at what the student's greeting looks like in that section, and try implementing your own Student() constructor that inherits all the features of Person(), and implements the different greeting() function.

Note: If you have trouble getting this to work, have a look at our finished version (see it running live also).

Object member summary

To summarize, you've basically got three types of property/method to worry about:

  1. Those defined inside a constructor function that are given to object instances. These are fairly easy to spot — in your own custom code, they are the members defined inside a constructor using the this.x = x type lines; in built in browser code, they are the members only available to object instances (usually created by calling a constructor using the new keyword, e.g. var myInstance = new myConstructor()).
  2. Those defined directly on the contructor themselves, that are available only on the constructor. These are commonly only available on built-in browser objects, and are recognised by being chained directly onto a constructor, not a instance. For example, Object.keys().
  3. Those defined on a constructor's prototype, which are inherited by all instances and inheriting object classes. These include any member defined on a Constructor's prototype property, e.g. myConstructor.prototype.x().

If you are not sure which is which, don't worry about it just yet — you are still learning, and familiarity will come with practise.

When would you use inheritance in JavaScript?

Particular after this last article, you might be thinking "woo, this is complicated". Well, you are right, prototypes and inheritance represent some of the most complex aspects of JavaScript, but a lot of JavaScript's power and flexibility comes from its object structure and inheritance, and it is worth understanding how it works.

In a way, you use inheritance all the time — whenever you use various features of a WebAPI , or methods/properties defined on a built-in browser object that you call on your strings, arrays, etc., you are implicitly using inheritance.

In terms of using inheritance in your own code, you probably won't use it that often, especially to begin with, and in small projects — it is a waste of time to use objects and inheritance just for the sake of it, when you don't need them. But as your code bases get larger, you are more likely to find a need for it. If you find yourself starting to create a number of objects that have similar features, then creating a generic object type to contain all the shared functionality and inheriting those features in more specialized object types can be convenient and useful.

Note: The act of putting common functionality into a generic object type so it can be inherited by others is sometimes called delegation — the specialized objects delegate that functionality to the generic object type. This is probably more accurate than calling it inheritance, as the "inherited" functionality is not copied to the objects that are doing the "inheriting". Instead it still remains in the generic object.

When using inheritance, you are advised to not have too many levels of inheritance, and to keep careful track of where you define your methods and properties. It is possible to start writing code that temporarily modifies the prototypes of built-in browser objects, but you should not do this unless you have a really good reason. Too much inheritance can lead to endless confusion, and endless pain when you try to debug such code.

Ultimately, objects are just another form of code reuse, like functions or loops, with their own specific roles and advantages. If you find yourself creating a bunch of related variables and functions and want to track them all together and package them neatly, an object is a good idea. Objects are also very useful when you want to pass a collection of data from one place to another. Both of these things can be achieved without use of contructors or inheritance. If you only need a single instance of an object, then you are probably better off just using an object literal, and you certainly don't need inheritance.

Summary

This article has covered the remainder of the core OOJS theory and syntax that we think you should know now. At this point you should understand JavaScript object and OOP basics, prototypes and prototypal inheritance, how to create classes (constructors) and object instances, add features to classes, and create subclasses that inherit from other classes.

In the next article we'll dive into a practical exercise, giving you some more practice in building your own fully-functional JavaScript objects.

See also

  • ObjectPlayground.com — A really useful interactive learning site for learning about objects.
  • Secrets of the JavaScript Ninja, Chapter 6 — A good book on advanced JavaScript concepts and techniques, by John Resig and Bear Bibeault. Chapter 6 covers aspects of prototypes and inheritance really well; you can probably track down a print or online copy fairly easily.
  • You Don't Know JS: this & Object Prototypes — Part of Kyle Simpson's excellent series of JavaScript manuals, Chapter 5 in particular looks at prototypes in much more detail than we do here. We've presented a simplified view in this series of articles aimed at beginners, whereas Kyle goes into great depth and provides a more complex but more accurate picture.

{{PreviousMenuNext("Learn/JavaScript/Objects/Object_prototypes", "Learn/JavaScript/Objects/Build_your_own", "Learn/JavaScript/Objects")}}

Revision Source

<div>{{draft}}{{LearnSidebar}}</div>

<div>{{PreviousMenuNext("Learn/JavaScript/Objects/Object_prototypes", "Learn/JavaScript/Objects/Build_your_own", "Learn/JavaScript/Objects")}}</div>

<p class="summary">With most of the gory details of OOJS now explained, this article shows how to create "child" object classes (constructors) that inherit features from their "parent" classes. In addition, we present some advice on when and where you might use OOJS.</p>

<table class="learn-box standard-table">
 <tbody>
  <tr>
   <th scope="row">Prerequisites:</th>
   <td>Basic computer literacy, a basic understanding of HTML and CSS, familiarity with JavaScript basics (see <a href="/en-US/docs/Learn/JavaScript/First_steps">First steps</a> and <a href="/en-US/docs/Learn/JavaScript/Building_blocks">Building blocks</a>) and OOJS basics (see <a href="/en-US/docs/Learn/JavaScript/Object-oriented/Introduction">Introduction to objects</a>).</td>
  </tr>
  <tr>
   <th scope="row">Objective:</th>
   <td>To understand how it is possible to implement inheritance in JavaScript.</td>
  </tr>
 </tbody>
</table>

<h2 id="Inheritance">Prototypal inheritance??</h2>

<p>So far we have seen some inheritance in action — we have seen how prototype chains work, and how members are inherited going up a chain. But mostly this has involved built-in browser functions. How do we create an object in JavaScript that inherits from another object?</p>

<p>Well, as mentioned before JavaScript is not a true object-oriented language. In such languages, you tend to define class objects of some kind, and you can then simply define which classes inherit from which other classes (see <a href="https://www.tutorialspoint.com/cplusplus/cpp_inheritance.htm">C++ inheritance</a> for some simple examples). In JavaScript it is not quite that simple — it is possible to create a system something this, but it is regarded as somewhat of a hack. And you must remember that such "inheriting" objects are not undergoing true inheritance (with functionality being copied over). Instead, the functionality they inherit is linked to via the prototype chain (often referred to as <strong>prototypal inheritance</strong>).</p>

<p>Let's explore how to do this with a concrete example.</p>

<h2 id="Getting_started">Getting started</h2>

<p>First of all, make youself a local copy of our <a href="https://github.com/mdn/learning-area/blob/master/javascript/oojs/advanced/oojs-class-inheritance-start.html">oojs-class-inheritance-start.html</a> file (see it <a href="https://mdn.github.io/learning-area/javascript/oojs/advanced/oojs-class-inheritance-start.html">running live</a> also). Inside here you'll find the same <code>Person()</code> constructor example that we've been using all the way through the module, with a slightly difference — we've defined only the properties inside the constructor:</p>

<pre class="brush: js">
function Person(first, last, age, gender, interests) {
  this.name = {
    first,
    last
  };
  this.age = age;
  this.gender = gender;
  this.interests = interests;
};</pre>

<p>The methods are <em>all</em> defined on the constructor's prototype, for example:</p>

<pre class="brush: js">
Person.prototype.greeting = function() {
  alert('Hi! I\'m ' + this.name.first + '.');
};</pre>

<p>So, say we wanted to create a <code>Teacher</code> class, like the one we described in our initial object-oriented definition, which inherits all the members from <code>Person</code>, but also includes:</p>

<ol>
 <li>A new property, <code>subject</code> — this will contain the subject the teacher teaches.</li>
 <li>An updated <code>greeting()</code> method, which sounds a bit more formal than the standard <code>greeting()</code> method — more suitable for a teacher addressing some students at school.</li>
</ol>

<h2 id="Defining_a_Teacher()_constructor">Defining a Teacher() constructor function</h2>

<p>The first thing we need to do is create a <code>Teacher()</code> constructor — add the following below the existing code:</p>

<pre class="brush: js">
function Teacher(first, last, age, gender, interests, subject) {
  Person.call(this, first, last, age, gender, interests);

  this.subject = subject;
}</pre>

<p>This looks similar to the Person constructor in many ways, but there is something strange here that we've not seen before — the <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call">call()</a></code> function. This function basically allows you to call a function defined somewhere else in the current context. The first parameter specifies the value of <code>this</code> that you want to use when running the function, and the other parameters specify the parameters that the function should have passed to it when it runs.</p>

<p>So in this case we are effectively running the <code>Person()</code> constructor function (see above) inside the <code>Teacher()</code> constructor function, resulting in the same properties being defined inside <code>Teacher()</code>, using the values of the parameters passed to <code>Teacher()</code>, not <code>Person()</code> (we are using simply <code>this</code> as the value of <code>this</code> passed to <code>call()</code>, meaning that <code>this</code> will be the <code>Teacher()</code> function).</p>

<p>The last line inside the constructor simply defines the new <code>subject</code> property that teachers are going to have, which generic people won't have.</p>

<p>As a note, we could have simply done this:</p>

<pre class="brush: js">
function Teacher(first, last, age, gender, interests, subject) {
  this.name = {
    first,
    last
  };
  this.age = age;
  this.gender = gender;
  this.interests = interests;
  this.subject = subject;
}</pre>

<p>But this is just redefining the properties anew, not inheriting them from <code>Person()</code>, so it defeats the point of what we are trying to do. It also takes more lines of code.</p>

<h2 id="Setting_Teacher()'s_prototype_and_constructor">Setting Teacher()'s prototype and constructor reference</h2>

<p>All is good so far, but we have a problem. We have defined a new constructor, and it has an empty <code>prototype</code> property by default. We need to get <code>Teacher()</code> to inherit the methods defined on <code>Person()</code>'s prototype. So how do we do that?</p>

<ol>
 <li>Add the following line below your previous addition:
  <pre class="brush: js">
Teacher.prototype = Object.create(Person.prototype);</pre>
  Here our friend <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create">create()</a></code> comes to the rescue again — in this case we are using it to create a new <code>prototype</code> property value (which is itself an object that contains properties and methods) with a prototype equal to <code>Person.protype</code>, and set that to be the value of <code>Teacher.prototype</code>. This means that <code>Teacher.prototype</code> will now inherit all the methods available on <code>Person.prototype</code>.</li>
 <li>We need to do one more thing before we move on — the <code>Teacher()</code> <code>prototype</code>'s constructor property is currently set as <code>Person()</code>, because of the way we inherited from it (this <a href="https://stackoverflow.com/questions/8453887/why-is-it-necessary-to-set-the-prototype-constructor">Stack Overflow post</a> has more information on why) — try saving your code, loading the page in a browser, and entering this into the JavaScript console to verify:
  <pre class="brush: js">
Teacher.prototype.constructor</pre>
 </li>
 <li>This can become a problem, so we need to set this right — you can do so by going back to your source code and adding the following line at the bottom:
  <pre class="brush: js">
Teacher.prototype.constructor = Teacher;</pre>
 </li>
 <li>Now if you save and refresh, entering <code>Teacher.prototype.constructor</code> should return <code>Teacher()</code>, as desired.</li>
</ol>

<h2 id="Giving_Teacher()_a_new_greeting()_function">Giving Teacher() a new greeting() function</h2>

<p>To finish off our code, we need to define a new <code>greeting()</code> function on the <code>Teacher()</code> constructor.</p>

<p>The easiest way to do this is to define it on <code>Teacher()</code>'s prototype — add the following at the bottom of your code:</p>

<pre class="brush: js">
Teacher.prototype.greeting = function() {
  var prefix;

  if(this.gender === 'male' || this.gender === 'Male' || this.gender === 'm' || this.gender === 'M') {
    prefix = 'Mr.';
  } else if(this.gender === 'female' || this.gender === 'Female' || this.gender === 'f' || this.gender === 'F') {
    prefix = 'Mrs.';
  } else {
    prefix = 'Mx.';
  }

  alert('Hello. My name is ' + prefix + ' ' + this.name.last + ', and I teach ' + this.subject + '.');
};</pre>

<p>This alerts the teacher's greeting, which also uses an appropriate name prefix for their gender, worked out using a conditional statement.</p>

<h2 id="Trying_the_example_out">Trying the example out</h2>

<p>Now you've entered all the code, try creating an object instance from <code>Teacher()</code> by putting the following at the bottom of your JavaScript (or something similar of your choosing):</p>

<pre class="brush: js">
var teacher1 = new Teacher('Dave', 'Griffiths', 31, 'male', ['football', 'cookery'], 'mathematics');</pre>

<p>Now save and refresh, and try accessing the properties and methods of your new <code>teacher1</code> object, for example:</p>

<pre class="brush: js">
teacher1.name.first;
teacher1.interests[0];
teacher1.bio();
teacher1.subject;
teacher1.greeting();</pre>

<p>These should all work just fine; the first three access members that were inherited from the generic <code>Person()</code> constructor (class), while the last two access members that are only available on the more specialised <code>Teacher()</code> constructor (class).</p>

<div class="note">
<p><strong>Note</strong>: If you have trouble getting this to work, compare your code to our <a href="https://github.com/mdn/learning-area/blob/master/javascript/oojs/advanced/oojs-class-inheritance-finished.html">finished version</a> (see it <a href="https://mdn.github.io/learning-area/javascript/oojs/advanced/oojs-class-inheritance-finished.html">running live</a> also).</p>
</div>

<p>The technique we covered here is a bit convoluted, and it is certainly not the only way to create inheriting classes in JavaScript, but it works ok, and it gives you a good idea about inheritance in JavaScript. You might also be interested in checking out some of the new {{glossary("ECMAScript")}} features that allow us to do inheritance more cleanly in JavaScript (see <a href="/en-US/docs/Web/JavaScript/Reference/Classes">Classes</a>). We didn't cover those here, as they are not yet supported very widely across browsers. All the other code constructs we discussed in this set of articles are supported as far back as IE9 or earlier, and there are ways to achieve earlier support than that.</p>

<p>A common way is to use a JavaScript library — most of the popular options have an easy set of functionaily available for doing inheritance more easily and quickly. <a href="https://coffeescript.org/#classes">CoffeeScript</a> for example provides <code>class</code>, <code>extends</code>, etc.</p>

<h2 id="A_further_exercise">A further exercise</h2>

<p>In our OOP theory section, we also included a <code>Student</code> class as a concept, which inherits all the features of <code>Person</code>, and also has a different <code>greeting()</code> method to <code>Person</code> that is much more informal than the <code>Teacher</code>'s greeting. Have a look at what the student's greeting looks like in that section, and try implementing your own <code>Student()</code> constructor that inherits all the features of <code>Person()</code>, and implements the different <code>greeting()</code> function.</p>

<div class="note">
<p><strong>Note</strong>: If you have trouble getting this to work, have a look at our <a href="https://github.com/mdn/learning-area/blob/master/javascript/oojs/advanced/oojs-class-inheritance-student.html">finished version</a> (see it <a href="https://mdn.github.io/learning-area/javascript/oojs/advanced/oojs-class-inheritance-student.html">running live</a> also).</p>
</div>

<h2 id="Object_member_summary">Object member summary</h2>

<p>To summarize, you've basically got three types of property/method to worry about:</p>

<ol>
 <li>Those defined inside a constructor function that are given to object instances. These are fairly easy to spot — in your own custom code, they are the members defined inside a constructor using the <code>this.x = x</code> type lines; in built in browser code, they are the members only available to object instances (usually created by calling a constructor using the <code>new</code> keyword, e.g. <code>var myInstance = new myConstructor()</code>).</li>
 <li>Those defined directly on the contructor themselves, that are available only on the constructor. These are commonly only available on built-in browser objects, and are recognised by being chained directly onto a constructor, <em>not</em> a instance. For example, <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys">Object.keys()</a></code>.</li>
 <li>Those defined on a constructor's prototype, which are inherited by all instances and inheriting object classes. These include any member defined on a Constructor's prototype property, e.g. <code>myConstructor.prototype.x()</code>.</li>
</ol>

<p>If you are not sure which is which, don't worry about it just yet — you are still learning, and familiarity will come with practise.</p>

<h2 id="When_would_you_use_inheritance_in_JavaScript">When would you use inheritance in JavaScript?</h2>

<p>Particular after this last article, you might be thinking "woo, this is complicated". Well, you are right, prototypes and inheritance represent some of the most complex aspects of JavaScript, but a lot of JavaScript's power and flexibility comes from its object structure and inheritance, and it is worth understanding how it works.</p>

<p>In a way, you use inheritance all the time — whenever you use various features of a WebAPI , or methods/properties defined on a built-in browser object that you call on your strings, arrays, etc., you are implicitly using inheritance.</p>

<p>In terms of using inheritance in your own code, you probably won't use it that often, especially to begin with, and in small projects — it is a waste of time to use objects and inheritance just for the sake of it, when you don't need them. But as your code bases get larger, you are more likely to find a need for it. If you find yourself starting to create a number of objects that have similar features, then creating a generic object type to contain all the shared functionality and inheriting those features in more specialized object types can be convenient and useful.</p>

<div class="note">
<p><strong>Note</strong>: The act of putting common functionality into a generic object type so it can be inherited by others is sometimes called <strong>delegation</strong> — the specialized objects delegate that functionality to the generic object type. This is probably more accurate than calling it <em>inheritance</em>, as the "inherited" functionality is not copied to the objects that are doing the "inheriting". Instead it still remains in the generic object.</p>
</div>

<p>When using inheritance, you are advised to not have too many levels of inheritance, and to keep careful track of where you define your methods and properties. It is possible to start writing code that temporarily modifies the prototypes of built-in browser objects, but you should not do this unless you have a really good reason. Too much inheritance can lead to endless confusion, and endless pain when you try to debug such code.</p>

<p>Ultimately, objects are just another form of code reuse, like functions or loops, with their own specific roles and advantages. If you find yourself creating a bunch of related variables and functions and want to track them all together and package them neatly, an object is a good idea. Objects are also very useful when you want to pass a collection of data from one place to another. Both of these things can be achieved without use of contructors or inheritance. If you only need a single instance of an object, then you are probably better off just using an object literal, and you certainly don't need inheritance.</p>

<ol>
</ol>

<h2 id="Summary">Summary</h2>

<p>This article has covered the remainder of the core OOJS theory and syntax that we think you should know now. At this point you should understand JavaScript object and OOP basics, prototypes and prototypal inheritance, how to create classes (constructors) and object instances, add features to classes, and create subclasses that inherit from other classes.</p>

<p>In the next article we'll dive into a practical exercise, giving you some more practice in building your own fully-functional JavaScript objects.</p>

<h2 id="See_also">See also</h2>

<ul>
 <li><a href="https://www.objectplayground.com/">ObjectPlayground.com</a> — A really useful interactive learning site for learning about objects.</li>
 <li><a href="https://www.amazon.com/gp/product/193398869X/">Secrets of the JavaScript Ninja</a>, Chapter 6 — A good book on advanced JavaScript concepts and techniques, by John Resig and Bear Bibeault. Chapter 6 covers aspects of prototypes and inheritance really well; you can probably track down a print or online copy fairly easily.</li>
 <li><a href="https://github.com/getify/You-Dont-Know-JS/blob/master/this%20&amp;%20object%20prototypes/README.md#you-dont-know-js-this--object-prototypes">You Don't Know JS: this &amp; Object Prototypes</a> — Part of Kyle Simpson's excellent series of JavaScript manuals, Chapter 5 in particular looks at prototypes in much more detail than we do here. We've presented a simplified view in this series of articles aimed at beginners, whereas Kyle goes into great depth and provides a more complex but more accurate picture.</li>
</ul>

<p>{{PreviousMenuNext("Learn/JavaScript/Objects/Object_prototypes", "Learn/JavaScript/Objects/Build_your_own", "Learn/JavaScript/Objects")}}</p>
Revert to this revision