In this tutorial, we will see how to Create Objects in JavaScript. Objects provide a way to group several values into a single value. The object internally uses a collection of key-value pairs to store values. JavaScript has several ways by which you can create an object. Let us explore that in detail.
There are several different ways to create new objects in Javascript
An object literal in JavaScript allows us to create plain JavaScript objects. It consists of a list of key-value pairs, each separated by a comma and wrapped inside curly braces.
To create a object using object literal syntax
var person = {
firstName: "Allie", //FirstName Property
lastName: "Grater", //lastName Property
age: 50, //age
getName : function () {
console.log(this.firstName + ' ' + this.lastName)
}
};
person.getName(); //Allie Grater
You can read more about Object Literal in JavaScript.
JavaScript object Constructor function allows us to create multiple similar objects easily. We invoke the constructor function using the new operator.
The constructor function is a regular JavaScript function that contains a recipe to create a new object. When we invoke it using the new operator it creates a new instance of the object and returns it.
JavaScript provides some built-in constructor functions. One of them is the Object constructor function. The return value of the Object() constructor a new object. Once we create a new create new object, we assign properties and methods to it.
const person = new Object();
person.firstName = 'Alex';
person.lastName = 'Ferguson';
person.getName = function () {
console.log(this.firstName + ' ' + this.lastName)
}
person.getName(); //Alex Ferguson
If you pass an object as the first argument to it, It will return it as it is.
const person = new Object ( {
firstName : 'Alex',
lastName: 'Ferguson',
getName: function() {
console.log(this.firstName+' '+this.lastName);
}
});
person.getName() //Alex Ferguson
Apart from JavaScript also have several built-in constructor functions like Function, boolean, Number, BigInt, Math, Date, etc. You can refer to the Complete list of built-in objects in JavaScript.
let str = new String(); // String Object
let num = new Number(); // Number object
let bool = new Boolean(); // Boolean object
Creating an new Array
let fruits = new Array(); // new Array object
fruits.push('Apple', 'Banana')
console.log(fruits) //["Apple", "Banana"]
//is same as
fruits =["Apple", "Banana"]
Apart from the built-in constructor functions, we can define our own constructor function. To Create constructor function
//Constructor function
function Person(firstName, lastName, age) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
this.fullName = function() {
return this.firstName + ' ' + this.lastName;
};
}
//Create a as many objects as you want
let alex = new Person('Alex', 'Ferguson', 50);
let santi = new Person('Santi', 'Argo', 40);
let sarah = new Person('Sarah', 'Moanees', 25);
You can refer to Constructor Function & New Operator in JavaScript
The Object.create() is useful, when you want to create a new object and also want to set an existing object as its Prototype. We pass the Prototype as the first argument to the Object.create() method.
The following code creates a new object alex and sets person as its prototype.
const person = {
fullName: function() {
console.log(this.firstName+' '+this.lastName);
}
};
const alex = Object.create(person);
alex.firstName = 'Alex';
alex.lastName = 'Ferguson';
alex.fullName() //Alex Ferguson
The Second argument to object.create is a property descriptors.
const person = {
fullName: function() {
console.log(this.firstName+' '+this.lastName);
}
};
descriptors= { firstName: { value: 'Alex' }, lastName: { value:'Ferguson' }}
const alex = Object.create(person, descriptors);
alex.fullName()
Use Object.assign() method to create a clone of another object (Source). But remember that it only copies its own properties which are enumerable from the Source object
The Object.assign() also allows copying from more than one source. Properties in the target object are overwritten by properties in the sources if they have the same key. Later sources’ properties overwrite earlier ones.
The following example, creates a new object from Object.assign
var src1 = { a: 10 };
var obj = Object.assign({}, src1);
console.log(obj )
Creating a new object from Multiple Sources.
var src1 = { a: 10 };
var src2 = { b: 20 };
var src3 = { a: 1, c:30 };
var obj = Object.assign({}, src1,src2,src3);
console.log(obj ) //{a: 1, b: 20, c: 30}
Target is an existing object.
var obj = { a:1,b:2,c:3,d:4}
var src1 = { a: 10 };
var src2 = { b: 20 };
var obj = Object.assign(obj, src1,src2);
console.log(obj ) //{a: 10, b: 20, c: 3, d: 4}
Classes in JavaScript were introduced with ES6. They are nothing but Syntactic sugar for the new and constructor function.
The following example shows you how to create a class in JavaScript. We can then use the new keyword to objects from the class.
class Person {
constructor(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
// Method
getName() {
return this.firstName +' '+ this.lastName;
}
}
const person = new Person('Alex', 'Ferguson');
console.log(person.getName()); // Alex Ferguson
Refer to Getters & Setters in JavaScript for more on accessor properties
Methods are like verbs. They perform actions.
Unlike the programming languages like C# & Java, Javascript allows us to store the function in a variable and use it later.
When we assign a function to a property, we call that property a method.
In the following example, we assign a function to the Property fullName
let person = {
firstName: "Allie",
lastName: "Grater",
age: 50,
fullName: function() {
return this.firstName + " " + this.lastName;
}
};
Read More