Objects - JavaScript Object Constructors
Posted by Superadmin on May 01 2023 04:31:26

JavaScript Object Constructors

By Asapu HarikaAsapu Harika
  

JavaScript Object Constructors

Introduction to JavaScript Object Constructors

Collection of unordered related data in the form of key: value pairs is referred as Objects in JavaScript, here keys can be variables or functions and called by the name properties and methods accordingly. Objects are different from primitive data types of JavaScript such as Number, Boolean, String, symbol, etc. which store only single value based on their data type. Whereas Objects can contain any combination of primitive data types and also objects, known as a reference data type.

Syntax:

function <function name> ( <attributes> ){
this.<name of the attribute> = <name of the attribute>;
………..
……….
}
var <object name> = new <function name> ( <values for attributes> )

Here, ‘this’ and ‘new’ are the required keywords for JavaScript object constructors.

Examples of JavaScript Object Constructors

Let us consider at a simple example to understand how a JavaScript object looks like:

function Company (name, age, id, project) {
this.name = name;
this.age = age;
this.id = id;
this.project = project;
}

In the above example, function name Company has attributes name, age, id, project

Constructor functions are named with uppercase first letter.

These constructors are similar to regular functions, the difference is we use them with new keyword. There are 2 different constructors, Array and Object which are the built-in constructors and custom constructors which define properties and methods for the objects. These constructors are useful while creating multiple similar objects with same properties and methods

To create an object type, we need to use and object constructor function, here Company is an example of object constructor function. Keyword ‘new’ is used to call the constructor function to create objects of same type.

For Example:

var customer = new Company ("Mayank", "30", "12031", "MetLife");

Here customer is the object created by calling the object constructor function using ‘new’ keyword. It creates an instance of Company assigning itself to a variable customer. Constructor Company is taking the arguments passed to it and attaching it to ‘this’ object, so when the constructor is invoked using ‘new’ keyword, the constructor’s ‘this’ is set to the object that ‘new’ returns which inclines to

var customer = {
name: Mayank
age: 30
id: 12031
project: MetLife
}

As customer object is an instance of constructor object Company, it ensures to receive correct type of data. We can also assign methods to the constructor which are accessible to all the objects created by object constructor. Using constructors, objects will be created in the basic structure and mistakes would be reduced without creating generic objects. Let us look at how object constructors initiated:

Object created with ‘new’ keyword and arguments are passed and the other is object being created using curly braces ‘{}’

var object_name = new Object();

Or

var object_name = new Object ("arg1", "arg2", "arg3");

Let us look at how properties are assigned to objects,

Using dot operator ( . ):

object_name.properties = value;

and by using third bracket i.e. ( [ ] )

object_name [ 'properties' ] = value;

Consider Student as an object constructor,

function Student (s1, s2, s3) {
this.s1 = s1;
this.s2 = s2;
this.s3 = s3;
}
Student.prototype.getSum = function () {
var total = this.s1+this.s2+this.s3
return total;
};
var sum = new Student(25,50,45);
console.log(sum.getSum());

Output:

JavaScript Object Constructors-1.1

Here, s1, s2, s3 are the marks of student in a class, getSum is a function used to calculate the total, an object is created with ‘new’ keyword and function getSum is accesses with object class.

We can add any new property or method directly to the object constructor which makes sure that object properties defined will have default values.

Built-in JavaScript Constructors

We have some built-in javascript constructors,

String Objects

Generally, strings are declared and initialized using a variable, but can also be created as objects with ‘new’ keyword

var name = "James";

or

var name = new String("James");

Number Objects

Numbers are also declared and initialized using a variable, but also can be created as objects with ‘new’ keyword

var id = 45;

or

var id = new Number(45);

Boolean Objects

Boolean are also declared and initialized using a variable, but also can be created as objects with ‘new’ keyword

var state = false;

or

var id = new Boolean(false);

Custom Constructor Functions

Constructors can also be used to make multiple objects with the same properties and methods, consider below example.

function Record (name, date){
this.name = name;
this.date = '[' + date + ']';
}
var record1 = new Record("Physics","22/12/2012");
var record2 = new Record("Chemistry","24/12/2013");
console.log (record1.name, record1.date);
console.log (record2.name, record2.date);

As the Record constructor expects 2 parameters,

Output:

JavaScript Object Constructors-1.3

Using constructor mode test, we can have a check if object was called using ‘new’ keyword or not, using ‘new. target’ property. This approach is used to make the syntax more flexible but without the ‘new’ keyword it sometimes becomes difficult to identify that user is creating a new object.

function Student(name) {
if (! new.target) {
return new Student(name);
}
this.name = name;
}
let jack = Student("Jack"); //redirects call to new User jack
console.log(jack.name);

Output:

Using constructor mode test -1.2

Constructors don’t have return statement, result is written to ‘this’. But if return statement occurs and is called with an object, ‘this’ will return the object. Return can be ignored if object is primitive. Most built-in constructors such as ‘Object’, ‘Regex’ and ‘Array’ are scope-safe. Scope-safe constructor is designed to return the result regardless object being called with ‘new’ or without ‘new’ keyword.

With this article, we can conclude that constructors are regular functions, but used with keyword ‘new’ which means creating an empty ‘this’ before declaring the parameters or arguments and returning the data which has been populated at the end. Looked into some of the examples and built in JavaScript constructors. Also learnt on how objects constructor can make multiple objects with same properties and methods and seen how constructors can be called with ‘new’ keyword or without ‘new’ keyword which are named as scope-safe constructors.