Ways to Create Objects in JavaScript
There are several ways to create objects in JavaScript. The Object data type plays a critical role in JS. An object is an unordered set of key-value pairs. May contain other objects.
1. Literal notation
const someObject1 = {};
Perhaps the most common and easiest way. Let’s add properties and methods
someObject1.name = "John";
someObject1.age = 25;
someObject1.run = function() {
console.log("run");
}
And now the same thing, but we will set properties and methods when creating
const someObject1 = {
name: "John",
age: 25,
run: function() {
console.log("run");
}
};
2. Object constructor
This method is not recommended for use, and it is better to use the previous one. Nevertheless, it exists. But the probability of meeting him is extremely small
const someObject2 = new Object();
After that we also set properties and methods.
someObject2.name = "Nick";
someObject2.age = 30;
someObject2.jump = function() {
console.log("jump");
}
3. Function constructor
We can write our constructor function and create objects using the new operator
function SomeObject3(name, age) {
this.name = name;
this.age = age;
}
SomeObject3.prototype.run = function() {
console.log("run");
}
Create an object
const someObject3 = new SomeObject3("Alex", 20);
4. Object.create() method
There is another way to create objects – using the Object.create() method. The first parameter, the required parameter, is the prototype of the created object, and the second optional parameter is the list of object properties. In order to create an object without a prototype, you must call the Object.create() method with the null parameter.
const someObject4 = Object.create(Object.prototype);
// the full analogue of Object.create (Object.prototype) is
const otherObject1 = {};
//object without prototype
const otherObject2 = Object.create(null);
5. Using classes
ES6 syntax provides writing classes in JavaScript. At its core, this is an analog of the third method – using the constructor function. Only with a simpler and clearer record.
class SomeObject5 {
constructor(name, age) {
this.name = name;
this.age = age;
}
run() {
console.log("run");
}
}
Let’s now create an object, or more precisely an instance of a class
const someObject5 = new SomeObject5("Alex", 20);
Similar posts:
-
Vue Accordion Component
A simple and lightweight Vue 3 accordion component plugin. Supports both global plugin registration and local component usage. Written in TypeScript. The accordion compon...
-
How to Detect the Operating System (OS) Using JavaScript
Sometimes it is necessary to determine the user's operating system. To use different CSS styles for different OS, or for some analytics, or for other purposes. There are ...
-
Smooth Scrolling to Anchor Using JavaScript
Smooth scrolling is a popular web design feature that enhances user experience by allowing seamless navigation between sections of a webpage. Instead of abrupt jumps, smo...
Leave a Reply