(JavaScript Tutorials for Beginners)
In this end-to-end example, you will learn – JavaScript tutorials for Beginners – JavaScript Constructor Function.
JavaScript Constructor Function
In this tutorial, you will learn about JavaScript constructor function with the help of examples.
In JavaScript, a constructor function is used to create an object. For example,
// constructor function
function Person () {
this.name = 'John',
this.age = 23
}
// create an object
let person = new Person();
In the above example, function Person()
is an object constructor function.
To create an object from a constructor function, we use the new
keyword.
Note: It is considered a good practice to capitalize the first letter of your constructor function.
Create Multiple Objects with Constructor Function
In JavaScript, you can create multiple objects from a constructor function. For example,
// constructor function
function Person () {
this.name = 'John',
this.age = 23,
this.greet = function () {
console.log('hello');
}
}
// create objects
let person1 = new Person();
let person2 = new Person();
// access properties
console.log(person1.name); // John
console.log(person2.name); // John
In the above program, two objects are created using the same constructor function.
JavaScript this Keyword
In JavaScript, when this
keyword is used in a constructor function, this
refers to the object when the object is created. For example,
// constructor function
function Person () {
this.name = 'John',
}
// create object
let person1 = new Person();
// access properties
console.log(person1.name); // John
Hence, when an object accesses the properties, it can directly access the property as person1.name
.
JavaScript Constructor Function Parameters
You can also create a constructor function with parameters. For example,
// constructor function
function Person (person_name, person_age, person_gender) {
// assigning parameter values to the calling object
this.name = person_name,
this.age = person_age,
this.gender = person_gender,
this.greet = function () {
return ('Hi' + ' ' + this.name);
}
}
// creating objects
let person1 = new Person('John', 23, 'male');
let person2 = new Person('Sam', 25, 'female');
// accessing properties
console.log(person1.name); // "John"
console.log(person2.name); // "Sam"
In the above example, we have passed arguments to the constructor function during the creation of the object.
let person1 = new Person('John', 23, 'male');
let person2 = new Person('Sam', 25, 'male');
This allows each object to have different properties. As shown above,
console.log(person1.name);
gives John
console.log(person2.name);
gives Sam
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
let person = {
name: 'Sam'
}
// using constructor function
function Person () {
this.name = 'Sam'
}
let person1 = new Person();
let person2 = new Person();
- 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. For example,
// using constructor function
function Person () {
this.name = 'Sam'
}
let person1 = new Person();
let person2 = new Person();
// adding new property to person1
person1.age = 20;
Now this age
property is unique to person1
object and is not available to person2
object.
However, 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. For example,
// using object lateral
let person = {
name: 'Sam'
}
console.log(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
When an object is created with an object literal, any object variable derived from that object will act as a clone of the original object. Hence, any change you make in one object will also reflect in the other object.
Adding Properties And Methods in an Object
You can add properties or methods in an object like this:
// constructor function
function Person () {
this.name = 'John',
this.age = 23
}
// creating objects
let person1 = new Person();
let person2 = new Person();
// adding property to person1 object
person1.gender = 'male';
// adding method to person1 object
person1.greet = function () {
console.log('hello');
}
person1.greet(); // hello
// Error code
// person2 doesn't have greet() method
person2.greet();
Output
hello Uncaught TypeError: person2.greet is not a function
In the above example, a new property gender
and a new method greet()
is added to the person1
object.
However, this new property and method is only added to object1
. You cannot access gender
or greet()
from object2
. Hence the program gives error when we try to access person2.greet();
JavaScript Object Prototype
You can also add properties and methods to a constructor function using a prototype. For example,
// constructor function
function Person () {
this.name = 'John',
this.age = 23
}
// creating objects
let person1 = new Person();
let person2 = new Person();
// adding new property to constructor function
Person.prototype.gender = 'Male';
console.log(person1.gender); // Male
console.log(person2.gender); // Male
To learn more about prototypes, visit JavaScript Prototype.
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
In JavaScript, strings can be created as an object by:
let name = new String ('John');
console.log(name); // "John"
In JavaScript, numbers can be created as an object by:
let number = new Number (57);
console.log(number); // 57
In JavaScript, booleans can be created as an object by:
let count = new Boolean(true);
console.log(count); // true
Note: It is recommended to use primitive data types and create them in a normal way, such as let name = 'John';
, let number = 57;
and let count = true;
You should not declare strings, numbers, and boolean values as objects because they slow down the program.
Note: In JavaScript, the keyword class
was introduced in ES6 (ES2015) that also allows us to create objects. Classes are similar to constructor functions in JavaScript. To learn more, visit JavaScript Classes.
Disclaimer: The information and code presented within this recipe/tutorial is only for educational and coaching purposes for beginners and developers. Anyone can practice and apply the recipe/tutorial presented here, but the reader is taking full responsibility for his/her actions. The author (content curator) of this recipe (code / program) has made every effort to ensure the accuracy of the information was correct at time of publication. The author (content curator) does not assume and hereby disclaims any liability to any party for any loss, damage, or disruption caused by errors or omissions, whether such errors or omissions result from accident, negligence, or any other cause. The information presented here could also be found in public knowledge domains.
Learn by Coding: v-Tutorials on Applied Machine Learning and Data Science for Beginners
Latest end-to-end Learn by Coding Projects (Jupyter Notebooks) in Python and R:
All Notebooks in One Bundle: Data Science Recipes and Examples in Python & R.
End-to-End Python Machine Learning Recipes & Examples.
End-to-End R Machine Learning Recipes & Examples.
Applied Statistics with R for Beginners and Business Professionals
Data Science and Machine Learning Projects in Python: Tabular Data Analytics
Data Science and Machine Learning Projects in R: Tabular Data Analytics
Python Machine Learning & Data Science Recipes: Learn by Coding
R Machine Learning & Data Science Recipes: Learn by Coding
Comparing Different Machine Learning Algorithms in Python for Classification (FREE)
There are 2000+ End-to-End Python & R Notebooks are available to build Professional Portfolio as a Data Scientist and/or Machine Learning Specialist. All Notebooks are only $29.95. We would like to request you to have a look at the website for FREE the end-to-end notebooks, and then decide whether you would like to purchase or not.