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:
-
Swipe Events on Touch Devices in JavaScript
Every day sensory devices are being introduced into our lives. These devices have specific events, unlike the desktop. One of these events is the swipe. Especially often ...
-
Drop down menu (jQuery)
Drop down menu can be done without JavaScript, only with the help of CSS. With :hover. But the JavaScript menu has its advantages. The most important thing is the delay i...
-
How to Detect the Operating System (OS) Using JavaScript
Sometimes it is necessary to detect the user’s operating system when building web applications or websites. This can be useful for applying different CSS styles, collecti...
Leave a Reply