Search This Blog

2024/03/26

Javascript : Constructor Function

Constructor Function:
In JavaScript, a constructor function is a special type of
function that is used to create and initialize objects.

Constructor functions are primarily used in conjunction with
the new keyword to create instances of a particular type of
object, often referred to as instances of a class

Lets see by Examples:

Code:

function Car(make, model, year) {
this.make = make;
this.model = model;
this.year = year;
this.start = function() {
console.log(`${this.make} ${this.model} (${this.year})
is starting.`);
};
}
const myCar = new Car('Toyota', 'Camry', 2020);
console.log(myCar.make); // Output: Toyota
myCar.start();

Explanation:

A constructor function is defined using the function keyword followed by a
name typically starting with a capital letter to distinguish it from regular
functions. Inside the constructor function, properties and methods can be
defined using this.

In above code it is done as follows.

function Car(make, model, year) {
this.make = make;
this.model = model;
this.year = year;
this.start = function() {
console.log(`${this.make} ${this.model} (${this.year}) is
starting.`);
};
}


Instances (objects) of a constructor function are created using the
new keyword followed by the constructor function name and arguments
(if any).In above code it is done as follows

const myCar = new Car('Toyota', 'Camry', 2020);

Each instance created from a constructor function has its own set of
properties and methods defined within the constructor function. These
properties and methods are accessible using dot notation.

In above code it is done as follows

console.log(myCar.make); // Output: Toyota
myCar.start();

Here myCar.start() is method while myCar.make is property.

Using prototype to add property or method:
JavaScript constructor functions also have a prototype property, which can
be used to add methods or properties that are shared among all instances
created from the constructor.Method added using prototype use its own instance
properties when running itself.

It is done as follows.
Car.prototype.stop = function() {
console.log(`${this.make} ${this.model} (${this.year}) is stopping.`);
};

Now to call the property just added above we call can call it on any instance
of object.

like below.

myCar.stop(); // Output: Toyota Camry (2020) is stopping.

Constructor Function are often used to create reusable templates for
creating multiple objects with similar properties and behaviors.


Create Objects: Constructor Function Vs Object Literal:
Object Literal is generally used to create a single object.
The constructor function is useful if you want to create
multiple objects. For example,

using object literal:
Code :
let person = {
name: 'Sam'
}
let student = person;
// changes the property of an object
student.name = 'John';

// changes the origins object property
console.log(person.name); // John
Output:
John

Explanation:
if an object is created with an object literal, and if a variable is
defined with that object value, any changes in variable value will
change the original object.

using constructor function
Code:
function Person () {
this.name = 'Sam'
}
let person1 = new Person();
let person2 = new Person();

// adding new property to person1
person1.age = 20;
console.log(person1.age)
console.log(person2.age)
Output:
20
undefined

Explanation:
Each object created from the constructor function is unique.
You can have the same properties as the constructor function
or add a new property to one particular object.
age property is unique to person1 object and is not available to
person2.

Replacing Constructor function by factory function:

Below Car function is a factory function rather than a constructor
function.

Consider Code below:

Code:
function Car(make, model, year) {
let propertyBag = {};
propertyBag.make = make;
propertyBag.model = model;
propertyBag.year = year;
propertyBag.start = function () {
console.log(`${propertyBag.make} ${propertyBag.model}
(${propertyBag.year}) is starting.`);
}
return propertyBag;
}
const myCar =Car("Toyota", "Camry", 2020);
console.log(myCar.make); // Output: Toyota
myCar.start();

const myIndianCar = Car("Mahindra", "Thar", 2024);
console.log(myIndianCar.make); // Output: Toyota
myIndianCar.start();
Output:
Toyota
Toyota Camry (2020) is starting.
Mahindra
Mahindra Thar (2024) is starting.

Note:
we are not using this in Car function,nor does we are using new to create
Object of Car.Attempt to add another function to Car after creation of
function doesn't work.

What is been tried?
Car.prototype.stop = function () {
console.log(`${this.make} ${this.model} (${this.year}) is
stopping.`);
};
myIndianCar.stop();

we get error that myIndianCar.stop is not a function.


Scenario where we want a clean slate without any inherited properties or
methods:

we can go like this
Code:
const obj = Object.create(null); // Create an object with null prototype
console.log(obj); // Output: [Object: null prototype] {}

Explanation:
In this example, we create an object obj using Object.create(null). By
passing null to Object.create, we explicitly set the prototype of obj to
null, resulting in an object with no prototype chain.

However, keep in mind that objects with null prototypes don't have access
to standard prototype methods or properties like toString, hasOwnProperty,
etc., because they don't inherit from Object.prototype.

If you need to create objects with custom prototypes or inherit from
built-in prototypes, you would typically use constructor functions or
object literals with prototype inheritance.

JavaScript Built-in Constructors:
JavaScript also has built-in constructors. Some of them are:

let a = new Object(); // A new Object object
let b = new String(); // A new String object
let c = new Number(); // A new Number object
let d = new Boolean(); // A new Boolean object


e.g.
const name = new String ('John');
console.log(name); // "John"

const number = new Number (57);
console.log(number); // 57

const count = new Boolean(true);
console.log(count); // true

let a = new Object({
"firstName":"sangram",
"lastName":"desai"
});
console.log(a)//{ firstName: 'sangram', lastName: 'desai' }

No comments:

Post a Comment