Inheritance in JavaScript. Basic code example open

Inheritance in JavaScript. Basic code example

Approved. Code works!
This is exactly the working code that is verified by the moderator or site administrators

Inheritance allows, when creating new types of objects, to imitate the functionality of already existing objects if necessary. For example, we might have a User object representing an individual user. And it can also be an Employee object, which represents the worker. But a worker can also be a user and therefore must have all of its properties and methods. For example:

Example of inheritance using prototypes

Let’s create a User object constructor:

   
    function User(name, age) {
        this.name = name;
        this.age = age;
        this.go = function () { document.write(this.name + " go"); }
        this.displayInfo = function () {
            document.write("Name: " + this.name + "; age: " + this.age);
        };
    }
    //Set properties for all user objects through the prototype
    User.prototype.maxage = 99;

Now let’s create the Employee constructor:

    function Employee(name, age, comp) {
        //we imitate the properties of the object using the call method
        User.call(this, name, age);

        //add a new property that is not in the inherited object
        this.company = comp;

        //reassign the displayInfo method that is in the inherited object
        this.displayInfo = function () {
            document.write("Name: " + this.name + "; age: " + this.age + "; company: " + this.company);
        };

    }

    //we inheritan the properties of the prototype
    Employee.prototype = Object.create(User.prototype);

Let’s call:

    var alex = new User("Alexander", 33);
    var bill = new Employee("Bill", 32, "Google");
    alex.go();//Alexander go
    bill.go();//Bill go
    alex.displayInfo();//Name: Alexander; age: 33;
    bill.displayInfo();//Name: Bill, age: 32; company: Google
    console.log(bill.maxage);//99

Example of inheritance using Class

class Animal {
  constructor(name) {
    this.name = name;
  }

  speak() {
    console.log(`${this.name} makes a sound.`);
  }
}

class Dog extends Animal {
  speak() {
    console.log(`${this.name} barks.`);
  }
}

const dog = new Dog("Buddy");
dog.speak(); // Output: "Buddy barks."

In this example, the Dog class inherits from the Animal class. The Dog class has its own speak method, which overrides the Animal class’s speak method.

0

More

Leave a Reply

Your email address will not be published. Required fields are marked *

How many?: 22 + 22

lil-code© | 2022 - 2024
Go Top
Authorization
*
*
Registration
*
*
*
*
Password generation