Updated October 13, 2023
Introduction to JavaScript Object Constructors
JavaScript Objects consist of key-value pairs, where developers define properties or methods using variables or functions. The keys represent these properties or methods. Objects are different from primitive data types of JavaScript, such as Numbers, Boolean, Strings, symbols, etc., which store only a single value based on their data type. Objects can contain any combination of primitive data types and objects known as reference data types.
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 a simple example to understand what 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
One should name constructor functions with an uppercase first letter.
These constructors are similar to regular functions; the difference is we use them with new keywords. 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 the same properties and methods.
To create an object type, we need to use an object constructor function. Here, Company is an example of an object constructor function. To create objects of the same type, one can use the ‘new’ keyword to invoke the constructor function.
For Example:
var customer = new Company ("Mayank", "30", "12031", "MetLife");
Using the ‘new’ keyword to call the object constructor function creates an object, which in this case is the customer. It creates an instance of the Company assigning itself to a variable customer. The constructor Company attaches the arguments passed to it to the ‘this’ object. Invoking the constructor with the ‘new’ keyword sets the ‘this’ of the constructor to the object returned by ‘new’. Therefore, the arguments passed to the constructor initialize the object.
var customer = {
name: Mayank
age: 30
id: 12031
project: MetLife
}
As the customer object is an instance of the constructor object Company, it ensures receiving the correct type of data. One can assign methods to the constructor, which will be accessible to all objects created by the object constructor. Using constructors helps create objects in a structured manner and reduces errors without creating generic objects. Let us look at how object constructors initiated:
One can create an object by passing arguments when using the ‘new’ keyword or by using curly braces ‘{}’ to create an object.
var object_name = new Object();
Or
var object_name = new Object ("arg1", "arg2", "arg3");
Let’s explore how to assign properties to objects.
Using dot operator ( . ):
object_name.properties = value;
and by using the 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:
Here, s1, s2, and s3 are the marks of students in a class, getSum is a function used to calculate the total, an object is created with a ‘new’ keyword, and the function getSum is accessed with object class.
We can add any new property or method directly to the object constructor, which makes sure that the object properties defined will have default values.
Built-in JavaScript Constructors
We have some built-in javascript constructors,
String Objects
Usually, one declares and initializes strings using a variable, but it is also possible to create strings as objects with the ‘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 the ‘new’ keyword
var id = 45;
or
var id = new Number(45);
Boolean Objects
Boolean is also declared and initialized using a variable but also can be created as objects with the ‘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 the 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:
Using the constructor mode test, we can check if the object was called using the ‘new’ keyword or not, using ‘new. target’ property. This approach makes the syntax more flexible, but without the ‘new’ keyword, it can sometimes be challenging to identify that the 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:
Constructors don’t have a return statement; the result is written as ‘this’. However, if a return statement occurs and is invoked with an object, ‘this’ will yield the object. Return can be ignored if the 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 is being called with ‘new’ or without the ‘new’ keyword.
This article allows us to conclude that constructors are regular functions. However, their usage involves the ‘new’ keyword, implying the creation of an empty ‘this’ before the parameter or argument declaration and the subsequent population of the data before returning it at the end. Looked into some of the examples and built-in JavaScript constructors. I also learned how object constructors can create multiple objects with the same properties and methods. I observed that constructors can be invoked with the ‘new’ keyword or without it, a concept known as scope-safe constructors.
Recommended Articles
This is a guide to JavaScript Object Constructors. Here we also discuss the Introduction and built-in javascript constructors along with different examples and its code implementation. You may also have a look at the following articles to learn more –