How to implement prototype inheritance with constructor functions

In this tutorial, you will learn how to implement prototype inheritance with constructor functions.

The JavaScript classes don't work like traditional classes in other languages like Java.
So instead, classes in JavaScript are just syntactic over. So they still implement prototype inheritance behind the program but with a syntax that makes more sense to people coming from other programming languages. And so that was basically the goal of adding classes to JavaScript.


So we can write the class and then the name of the class. And let's actually call it User then curly braces is to add a constructor method.

 




constructor(firstName, lastName , age)




So just like this, this constructor actually works in a pretty similar way as a constructor function, like the previous article JavaScript constructor function but this one is actually a method of this class. And in fact, it needs to be called a constructor. So that is the rule.

But just like in constructor functions, we pass in arguments basically for the properties that we want the object to have. So that's again firstName, and then lastName and age.

Now, creating a new object actually also works in the exact same way as before the previous article:Javascript Constructor function and the new Operator with examples.

 

 




const User1 = new User('chandra','kumar',1993);



So using the new operator this constructor will automatically be called.



class User
{
 constructor(firstName, lastName , age)
{
    this.firstName = firstName;
    this.lastName = lastName;
    this.age = age;
}

const User1 = new User('chandra','kumar',1993);
console.log(User1);

Output:



User {firstName: 'chandra', lastName: 'kumar', age: 1993}
  

Calculate Present Age function userAge() - using to calculate the age of the user class.


class User
{
 constructor(firstName, lastName , age)
{
    this.firstName = firstName;
    this.lastName = lastName;
    this.age = age;
}
userAge()
{
    console.log(2022 - this.age);
}
}

const User1 = new User('chandra','kumar',1993);
console.log(User1);
User1.userAge();

Output:



User {firstName: 'chandra', lastName: 'kumar', age: 1993}

29


Implement Prototype with Construction Function



class User
{
 constructor(firstName, lastName , age)
{
    this.firstName = firstName;
    this.lastName = lastName;
    this.age = age;
}
userAge()
{
    console.log(2022 - this.age);
}
}

const User1 = new User('chandra','kumar',1993);
User.prototype.greet = function() {
console.log(`hello ${this.firstName}`);
};

User1.greet();


hello chandra


I hope you will learn how to implement prototype inheritance with constructor functions and just copy the code and paste on your editor and run it.

Post a Comment

Previous Post Next Post