DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
Securing Your Software Supply Chain with JFrog and Azure
Register Today

Trending

  • The SPACE Framework for Developer Productivity
  • How To Use Geo-Partitioning to Comply With Data Regulations and Deliver Low Latency Globally
  • Seven Steps To Deploy Kedro Pipelines on Amazon EMR
  • Revolutionizing Algorithmic Trading: The Power of Reinforcement Learning

Trending

  • The SPACE Framework for Developer Productivity
  • How To Use Geo-Partitioning to Comply With Data Regulations and Deliver Low Latency Globally
  • Seven Steps To Deploy Kedro Pipelines on Amazon EMR
  • Revolutionizing Algorithmic Trading: The Power of Reinforcement Learning
  1. DZone
  2. Coding
  3. Languages
  4. How to Create Basic Inheritance in JavaScript Constructors

How to Create Basic Inheritance in JavaScript Constructors

Creating inheritance between two JavaScript objects can be tricky business. Read on to learn how to solve this problem.

Dhanajay Kumar user avatar by
Dhanajay Kumar
·
Mar. 11, 19 · Tutorial
Like (1)
Save
Tweet
Share
11.10K Views

Join the DZone community and get the full member experience.

Join For Free

There are four ways to create an object in JavaScript. They are as follows:

  1. Object as literal
  2. Constructor Invocation Pattern
  3. The create() method
  4. Using class after ES6

The implementation of inheritance varies according to the object creation method. In this post, I am going to explain creating inheritance between a function constructor.

Let’s say you have a function:

function animal(name, age) {
    this.name = name;
    this.age = age;
}

If you call the animal function using the new operator, an object will be created. This way creating objects is also known as the “Constructor Invocation Pattern.”

var dog = new animal('foo', 5);
console.log(dog);
var cat = new animal('koo', 3);
console.log(cat);

The dog and cat objects both have their own names and age properties. If you want a property or method to be shared across all objects, add that to the prototype of the function.

animal.prototype.canRun = function () {
    console.log('yes ' + this.name + ' can run !');
}

Using the JavaScript prototype chain, both the dog and cat objects can access the canRun method.

var dog = new animal('foo', 5);
dog.canRun(); // yes foo can run

var cat = new animal('koo', 3);
cat.canRun(); // yes koo can run

Next, let us create another constructor – human:

function human(name, age, money) {
    this.name = name ;
    this.age = age ; 
    this.money = money;
}
human.prototype.canEarn = function () {
    console.log('yes ' + this.name + 'can earn');
}

At this point in time, the human and animal functions do not have any relationship. However, we know that humans are also animals. There are two problems with the human constructor.

  1. It has duplicate code for name and ageinitialization. It should use theanimal constructor for this purpose.
  2. It does not have any links with the animal constructor.

The above problems can be removed by creating inheritance between the animal and human function constructors.

You can solve Problem 1 of the code duplication issue by modifying the human function as shown below:

function human(name, age, money) {
    animal.call(this, name, age);
    this.money = money;
}

Now, in the human function, we are using the call method to manually pass a current object as a value of this in the animal function. This approach is also called the Indirect Invocation Pattern. Now, an object instance for human can be created as shown below:

var h1 = new human('dj', 30, '2000 $');
console.log(h1); 

So far, we have solved Problem 1 of our code duplication issue; however, the human function is still not linked to the animal function. If you try to call the canRun method on the  h1 object, JavaScript will throw you an error.

h1.canRun(); // throw error canRun is not a function 

You can fix this problem by linking the prototype of the human function with the prototype of theanimal function constructor. There are two ways to do that.

  1. Using __proto__. 
  2. Using the Object.create() method.

You can link the prototype of the function constructors using Object.create() as shown below:

human.prototype = Object.create(animal.prototype);

You can link the prototype of the function constructors using __proto__ as shown below:

human.prototype.__proto__ = animal.prototype;

I would prefer the Object.create() method because __proto__ may not be supported in many browsers. After linking the prototypes in one way, you have created inheritance between the animal and human function constructors. The object instance of human can read all the properties of the animal function and execute theanimal function's methods.

For your reference, the full source code to implement inheritance between function constructors is listed below:

function animal(name, age) {
    this.name = name;
    this.age = age;
}

animal.prototype.canRun = function () {
    console.log('yes ' + this.name + ' can run !');
}

var dog = new animal('foo', 5);
dog.canRun();

var cat = new animal('koo', 3);
cat.canRun();
function human(name, age, money) {
    animal.call(this, name, age);
    this.money = money;
}

human.prototype = Object.create(animal.prototype);

human.prototype.canEarn = function () {
    console.log('yes ' + this.name + 'can earn');
}
// human.prototype.__proto__ = animal.prototype;
var h1 = new human('dj', 30, '2000 $');
h1.canRun();
h1.canEarn();

To create inheritance between function constructors, always perform the following two actions:

  1. Call the parent constructor using call or apply.
  2. Link the prototype of the child constructor to the parent constructor prototype.

I hope now you understand how to implement inheritance between function constructors in JavaScript.

Inheritance (object-oriented programming) JavaScript Object (computer science) Prototype

Published at DZone with permission of Dhanajay Kumar, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Trending

  • The SPACE Framework for Developer Productivity
  • How To Use Geo-Partitioning to Comply With Data Regulations and Deliver Low Latency Globally
  • Seven Steps To Deploy Kedro Pipelines on Amazon EMR
  • Revolutionizing Algorithmic Trading: The Power of Reinforcement Learning

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com

Let's be friends: