in

Understanding JavaScript constructors

How to Set Up TypeScript in Node

[ad_1]

JavaScript is an established language, but ES6 just added support for traditional object-oriented programming (OOP). Until features like class declarations were added, JavaScript used a little-known prototype-based paradigm to handle his OOP. However, both approaches allow you to create complex applications that use object-based functionality.

Constructors in prototype JavaScript are very similar to other functions. The main difference is that you can use its constructor function to create an object.


What is a constructor in JavaScript

Laptop showing lines of code in IDE

Constructors are one of the basic concepts of object-oriented programming. A constructor is a function that can be used to create an instance of an object. A constructor not only creates a new object, but also specifies the properties and behaviors that belong to it.

Constructor syntax

 function NameOfConstructor() {
    this.property1 = "Property1";
    this.property2 = "Property2";
    this.property3 = "Property3";
}

You can create a constructor with function Keyword because it’s basically like any other function. However, constructors follow these rules:

  1. Use the name of the constructor with a capital letter to distinguish it from other functions.
  2. the constructor is this Keywords are different. in the constructor, this References the new object that the constructor creates.
  3. Unlike JavaScript functions, constructors define properties and behavior instead of returning values.

Create a new object using a constructor

In JavaScript, it’s easy to create objects using constructors. Here’s a simple constructor followed by a call.

 function Student() {
    this.name = "Gloria";
    this.gender = "Female";
    this.age = 19;
}

let femaleStudent = new Student();

In this example, Female student An object created from student constructor.use new A keyword for calling a function as a constructor. This keyword tells JavaScript to create a new instance. studentDo not call this function without the . new keyword this Inside the constructor, don’t point to the new object. After construction Female student has all the properties of studentYou can access and modify these properties just like any other object.

Important things to know about JavaScript constructors

Working with constructors can be both very tedious and trivial. Here are some important things a developer should know about working with constructors.

Using Constructors with Arguments

You can extend the constructor to accept arguments. This is very important if you want to write responsive and flexible code.

When you create an object from a constructor, the object inherits all properties declared in the constructor. for example, Female student I have the property I created above name, sexand Year with a fixed initial value. You can manually change each property, but this can be a tedious task if you write a program that uses many objects.

Thankfully, JavaScript constructors can accept parameters just like any other function. can be changed. student Constructor accepting two parameters:

 function Student(name, gender) {
    this.name = name;
    this.gender = gender;
    this.age = 19;
}

All objects created from above are Year set to 19. If you have properties that you want all objects to have, you can design your constructors this way.

You can now define unique objects from the same constructor by passing different arguments.

Arguments make the constructor more flexible. Saves time and encourages clean code.

Defining Object Methods

A method is an object property that is a function. Methods enhance OOP code because they add different behaviors to objects. For example:

 function Student(name, gender) {
    this.name = name;
    this.gender = gender;
    this.age = 19 ;

    this.sayName = function () {
        return `My Name is ${name}`;
    }
}

The above adds the function say the name to the constructor.

Suppose you use this constructor to create an object that you store in a variable. Female student. Then you can call this function with the code below.

 femaleStudent.sayName() 

prototype

previously created student all instances of which Year property with a value of 19. This will result in duplicate variables for each student Instances you create.

To avoid this duplication, JavaScript uses the concept of prototypes. All objects created from a constructor share the properties of its prototype.can add Year to properties student Prototype as shown below:

 Student.prototype.age = 19; 

This will allow all instances student I have Year property.declare Prototype properties It’s a way to reduce duplicate code in your application. Make your code as standard as possible.

Prototype property can be an object

You can add the Prototype property separately as explained above. However, this can be inconvenient if you have many properties to add.

Alternatively, you can include all desired properties in a new object. This allows you to set all properties at once. for example:

 Student.prototype = {
    age: 19,
    race: "White",
    disability: "None"
}

don’t forget to set constructor Properties when setting the prototype to a new object.

 Student.prototype = { 
    constructor: Student,
    age: 19,
    race: "White",
    disability: "None"
}

You can use this property to find out which constructor function created the instance.

supertypes and inheritance

Inheritance It is a method that programmers employ to reduce errors in their applications.that’s how to stick to Don’t repeat (DRY) principle.

Suppose we have two constructors—student and teacher— have two similar prototype properties.

 Student.prototype = { 
    constructor: Student,

    sayName: function () {
        return `My Name is ${name}`;
    }
}

Teacher.prototype = {
    constructor: Teacher,

    sayName: function () {
        return `My Name is ${name}`;
    }
}

Both of these constructors are say the name method, same. To avoid this unnecessary duplication, super type.

 function IndividualDetails(){};

IndividualDetails.prototype = {
    constructor: IndividualDetails,

    sayName: function () {
        return `My Name is ${name}`;
    }
};

then you can remove say the name from both constructors.

To inherit properties from a supertype, use Object. create(). Sets the prototype of both constructors to an instance of the supertype. in this case, student and teacher Convert the prototype to an instance of IndividualDetails.

yes this:

 Student.prototype = Object.create(IndividualDetails.prototype);
Teacher.prototype = Object.create(IndividualDetails.prototype);

By doing this, student and teacher inherits all properties of its supertype, personal details.

This is how you practice DRY in OOP using supertypes.

Constructor is a game changer

Constructors are an important component of JavaScript, and mastering their functionality is essential for developing OOP JavaScript applications. Constructors can be used to create objects that share properties and methods. You can also use inheritance to define object hierarchies.

In ES6, class Keywords for defining classic object-oriented classes. This version of JavaScript is constructor keyword.

[ad_2]

Source link

What do you think?

Leave a Reply

GIPHY App Key not set. Please check settings

    Lo2MQcpfnzchNRmLooMX88 1200 80

    Top website builders for WordPress in 2022

    smsf adviser logo

    Downsizer Bill Enters Senate