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:
-
Converting an Image to Base64 Using JavaScript
Converting an image to a Base64 string in JavaScript can be extremely useful in many modern web development scenarios. One of the most common reasons for using Base64 is ...
-
How to Detect Scroll Direction on a Page Using JavaScript
Sometimes it is necessary to detect the direction of vertical scrolling on a website in order to dynamically change the behavior of interface elements. For example, this ...
-
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...
Leave a Reply