1. Overview
In this article, we will discuss four different ways to create objects in Javascript.
In real life, a car is an object. A car has properties like weight and color, and methods like start() and stop():
Object | Properties | Methods |
---|---|---|
car.name = Fiat car.model = 500 car.weight = 850kg car.color = white | car.start() car.drive() car.brake() car.stop() |
All cars have the same properties, but the property values differ from car to car.
All cars have the same methods, but the methods are performed at different times.
All cars have the same methods, but the methods are performed at different times.
In JavaScript, almost "everything" is an object.
- Booleans can be objects (if defined with the new keyword)
- Numbers can be objects (if defined with the new keyword)
- Strings can be objects (if defined with the new keyword)
- Dates are always objects
- Maths are always objects
- Regular expressions are always objects
- Arrays are always objects
- Functions are always objects
- Objects are always objects
All JavaScript values, except primitives, are objects.
For the best learning experience, I highly recommended that you open a console (which, in Chrome and Firefox, can be done by pressing Ctrl+Shift+I), navigate to the "console" tab, copy-and-paste each JavaScript code example from this guide, and run it by pressing the Enter/Return key.
For the best learning experience, I highly recommended that you open a console (which, in Chrome and Firefox, can be done by pressing Ctrl+Shift+I), navigate to the "console" tab, copy-and-paste each JavaScript code example from this guide, and run it by pressing the Enter/Return key.
2. Four Ways to Create Objects in JavaScript
- Using object literals or object initializers
- Using a constructor function
- Using the Object.create() method
- Using ES 6 Class
2.1. Using object literals or object initializers
Using object literals is the simplest way to create an object in Javascript. An object literal also called an object initializer, is a comma-separated set of paired names and values.
Let's create a Javascript object using an object literal:
// using Object Literals
var user = {
firstName : 'Ramesh',
lastName : 'Fadatare',
emailId : 'ramesh@gmail.com',
age : 29,
getFullName : function (){
return user.firstName + " " + user.lastName;
}
}
console.log(JSON.stringify(user));
console.log(user.getFullName());
// access object properties
console.log('firstName :', user.firstName);
console.log('lastName :', user.lastName);
console.log('emailId :', user.emailId);
console.log('age :', user.age);
Output:
{"firstName":"Ramesh","lastName":"Fadatare","emailId":"ramesh@gmail.com","age":29}
Ramesh Fadatare
firstName : Ramesh
lastName : Fadatare
emailId : ramesh@gmail.com
age : 29
You can test above code in browser console:
2.2. Using a constructor function
The second way to create an object is to use the constructor function. If you call a function using a new operator, the function acts as a constructor and returns an object.
Below two steps define and create an object:
- Define the object type by writing a constructor function. There is a strong convention, with good reason, to use a capital initial letter.
- Create an instance of the object with a new keyword.
// using constructor function
function User(firstName, lastName, emailId, age){
this.firstName = firstName;
this.lastName = lastName;
this.emailId = emailId;
this.age = age;
}
var user1 = new User('Ramesh', 'Fadatare', 'ramesh24@gmail.com', 29);
var user2 = new User('John', 'Cena', 'john@gmail.com', 45);
var user3 = new User('Tony', 'Stark', 'tony@gmail.com', 52);
console.log(user1);
console.log(user2);
console.log(user3);
Output:
User {firstName: "Ramesh", lastName: "Fadatare", emailId: "ramesh24@gmail.com", age: 29}
User {firstName: "John", lastName: "Cena", emailId: "john@gmail.com", age: 45}
User {firstName: "Tony", lastName: "Stark", emailId: "tony@gmail.com", age: 52}
You can test above code in browser console:
2.3. Using the Object.create() method
Objects can also be created using the Object.create() method. This method can be very useful, because it allows you to choose the prototype object for the object you want to create, without having to define a constructor function.
// using Object.create Method
var Employee = {
firstName : 'Ramesh',
lastName : 'Fadatare',
emailId : 'ramesh@gmail.com',
age : 29,
getFullName : function (){
return user.firstName + " " + user.lastName;
}
}
var employee1 = Object.create(Employee);
// access object properties
console.log('firstName :', employee1.firstName);
console.log('lastName :', employee1.lastName);
console.log('emailId :', employee1.emailId);
console.log('age :', employee1.age);
Output:
firstName : Ramesh
lastName : Fadatare
emailId : ramesh@gmail.com
age : 29
More examples:
// Animal properties and method encapsulation
var Animal = {
type: 'Invertebrates', // Default value of properties
displayType: function() { // Method which will display type of Animal
console.log(this.type);
}
};
// Create new animal type called animal1
var animal1 = Object.create(Animal);
animal1.displayType(); // Output:Invertebrates
// Create new animal type called Fishes
var fish = Object.create(Animal);
fish.type = 'Fishes';
fish.displayType(); // Output:Fishes
2.4. Using ES 6 Class
ECMAScript 6 introduced the class keyword to create classes in JavaScript. Now you can use the class attribute to create a class in JavaScript instead of a function constructor, and use the new operator to create an instance. Read more about Javascript classes at Guide to JavaScript Classes.
Example: Let's create Employee class:
class Employee {
constructor(firstName, lastName, emailId, age){
this.firstName = firstName;
this.lastName = lastName;
this.emailId = emailId;
this.age = age;
}
getFullName(){
return this.firstName + " " + this.lastName;
}
getFirstName(){
return this.firstName;
}
}
Now, we create an object of Employee class and access its methods:
const employee = new Employee('Ramesh', 'Fadatare', 'ramesh@gmail.com', 29);
console.log(employee.getFirstName());
console.log(employee.getFullName());
Let's create more examples of Javascript classes:
class Rectangle {
constructor(height, width) {
this.height = height;
this.width = width;
}
// Getter
get area() {
return this.calcArea();
}
// Method
calcArea() {
return this.height * this.width;
}
}
const square = new Rectangle(10, 10);
console.log(square.area); // 100
3. Conclusion
We have seen four different ways to create an object in JavaScript - using object literals, using the function constructor, using the Object.create() method, and using the class keyword (which is almost the same as using a function constructor). The Object.create method is very useful when you need to create an object using an existing object as a prototype.
In this next article, you will learn a lot about Javascript classes at Guide to JavaScript Classes.
Check out all Javascript articles at JavaScript Tutorial
Comments
Post a Comment
Leave Comment