Creating objects in JavaScript (original) (raw)
Last Updated : 13 Aug, 2024
An object in JavaScript is a collection of key-value pairs, where keys are strings (properties) and values can be any data type. Objects can be created using object literals, constructors, or classes. Properties are defined with key-value pairs, and methods are functions defined within the object, enabling encapsulation and organization of data and behavior.
These are the following 4 ways:
Table of Content
- Creating object with a constructor
- Using object literals
- Creating object with Object.create() method
- Using es6 classes
**Creating object with a constructor
One of the easiest ways to instantiate an object is in JavaScript. Constructor is nothing but a function and with the help of a new keyword, the constructor function allows to creation of multiple objects of the same flavor as shown below:
**Example: This example shows the implementation of the above-explained approach.
javascript `
// Simple function function vehicle(name, maker, engine) { this.name = name; this.maker = maker; this.engine = engine; } // New keyword to create an object let car = new vehicle('GT', 'BMW', '1998cc'); // Property accessors console.log(car.name); console.log(car.maker); console.log(car['engine']);
`
**Explanation:
- **Class Components: A class in OOP has parameters and member functions, encapsulating attributes and behaviors.
- **Constructor Function: In a class method, parameters (e.g., name, maker, engine) use this to differentiate between class attributes and argument values.
- **Object Creation: Create an object (e.g., obj) from the class, initialize it, and call its methods to use the class functionality.
**Using object literals
Using object literals to create objects in JavaScript involves defining an object directly with key-value pairs inside curly braces {}. This method is concise and straightforward, allowing you to quickly create objects with properties and methods, enhancing code readability.
**Example: This example shows the implementation of the above-explained approach.
javascript `
// Creating js objects with object literal let car = { name: 'GT', maker: 'BMW', engine: '1998cc' }; // Property accessor console.log(car.name); //dot notation console.log(car['maker']); //bracket notation
`
**Explanation:
- In the above code example we Created a car object using an object literal with properties like name, maker, and engine.
- Used dot notation and bracket notation to access properties of the car object.
Now let’s see how we can add more properties to an already defined object:
javascript `
let car = { name: 'GT', maker: 'BMW', engine: '1998cc' }; // Adding property to the object car.brakesType = 'All Disc'; console.log(car);
`
Output
{ name: 'GT', maker: 'BMW', engine: '1998cc', brakesType: 'All Disc' }
Methods can also be part of the object while creation or can be added later like properties as shown below:
javascript `
// Adding methods to the car object
let car = {
name : 'GT',
maker : 'BMW',
engine : '1998cc',
start : function(){
console.log('Starting the engine...');
}
};
car.start();
// Adding method stop() later to the object
car.stop = function() {
console.log('Applying Brake...');
}
car.stop();
`
Output
Starting the engine... Applying Brake...
**Explanation: In the above code start method was added to the car object and later called by the _car.start() and also the stop method was added too after the object was already declared.
**Creating object with Object.create() Method
The Object.create() method in JavaScript creates a new object using an existing object as its prototype. This approach allows the new object to inherit properties and methods from the prototype object, enabling inheritance-like behavior. It’s useful for creating objects with shared behaviors while maintaining unique properties.
**Example: This example shows the implementation of the above-explained approach.
javascript ``
const coder = {
isStudying : false,
printIntroduction : function(){
console.log(My name is <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mrow><mi>t</mi><mi>h</mi><mi>i</mi><mi>s</mi><mi mathvariant="normal">.</mi><mi>n</mi><mi>a</mi><mi>m</mi><mi>e</mi></mrow><mi mathvariant="normal">.</mi><mi>A</mi><mi>m</mi><mi>I</mi><mi>s</mi><mi>t</mi><mi>u</mi><mi>d</mi><mi>y</mi><mi>i</mi><mi>n</mi><mi>g</mi><mo stretchy="false">?</mo><mo>:</mo></mrow><annotation encoding="application/x-tex">{this.name}. Am I studying?: </annotation></semantics></math></span><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.8889em;vertical-align:-0.1944em;"></span><span class="mord"><span class="mord mathnormal">t</span><span class="mord mathnormal">hi</span><span class="mord mathnormal">s</span><span class="mord">.</span><span class="mord mathnormal">nam</span><span class="mord mathnormal">e</span></span><span class="mord">.</span><span class="mord mathnormal">A</span><span class="mord mathnormal">m</span><span class="mord mathnormal" style="margin-right:0.07847em;">I</span><span class="mord mathnormal">s</span><span class="mord mathnormal">t</span><span class="mord mathnormal">u</span><span class="mord mathnormal">d</span><span class="mord mathnormal" style="margin-right:0.03588em;">y</span><span class="mord mathnormal">in</span><span class="mord mathnormal" style="margin-right:0.03588em;">g</span><span class="mclose">?</span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">:</span></span></span></span>{this.isStudying}
);
}
};
const me = Object.create(coder);
me.name = 'Mukul';
me.isStudying = true;
me.printIntroduction();
``
Output
My name is Mukul. Am I studying?: true
**Using es6 classes
Using ES6 classes to create objects in JavaScript involves defining a class with a constructor to initialize properties and methods. Objects are then instantiated from the class using the new keyword, offering a more structured and OOP-like approach to object creation.
**Example: This example the Vehicle class creates objects with name, maker, and engine properties. car1 is an instance with name set to GT.
javascript `
// Using es6 classes class Vehicle { constructor(name, maker, engine) { this.name = name; this.maker = maker; this.engine = engine; } }
let car1 = new Vehicle('GT', 'BMW', '1998cc');
console.log(car1.name); //GT
`