27 February 2024

3 Simple Ways to Create Objects in JavaScript

By usamerica_us

So, you want to learn how to create objects in JavaScript? Great! Let me show you three easy ways to do it. Brace yourself, because this is going to be super fun!

In JavaScript, we can create objects using curly braces. But wait, there’s more! You see, there are actually a few different ways to create objects, and you’ll definitely want to know all of them. Trust me, it’s going to be worth it!

First, let’s talk about built-in objects. These are objects that already exist in JavaScript, and we can use them to do all sorts of cool things. For example, there’s an object called “Date” that can give us information about dates. So if we want to display the current date on a webpage, we need to create an instance of the Date object. This instance will have all the necessary information about the current date.

In JavaScript, I discovered a fascinating feature that allows me to create my very own objects and generate new instances of those objects on the fly. It’s remarkable to think that in JavaScript, every single thing is an object and that each object has a common ancestor called Object. This concept opens up incredible possibilities for creating unique and specialized objects.

1. The Magic of the new Operator

To bring these objects to life, I’ve learned to use a powerful tool called the new operator. This operator is a well-known method for creating fresh object instances.

To wield the new operator effectively, you need something called a constructor. A constructor is like a magic spell that assembles a brand-new instance of an object. The syntax is quite simple:

new constructor()

When you create an object in JavaScript, you can use a constructor to change or add properties to it. The constructor has the same name as the object it belongs to. Let me show you an example using the Date object:

“`javascript

dt = new Date(2017, 0 , 1)

console.log(dt) // Sun Jan 01 2017 00:00:00 GMT+0100

“`

In this code, `Date()` is the constructor we use to create a new Date object. Different constructors can take different arguments to create object instances with varied attributes.

However, not all built-in objects in JavaScript have a constructor like the Date object. Examples of objects that don’t come with a constructor are Math, JSON, and Reflect. Despite not having a constructor, they are still ordinary objects.

When it comes to built-in objects with constructors, Symbol is a bit different. You can’t use the constructor style to create a new Symbol instance. Instead, you need to call it as a function, which will give you a fresh Symbol value.

Now, not all built-in objects with constructors require the new operator for instantiation. Functions, Arrays, Errors, and Regular Expressions can also be called as functions, without using new, and they’ll happily create and return a new object instance.

2. The Reflect object

Hey, backend programmers! You might already be familiar with Reflection APIs. These cool tools let you inspect and update the most basic parts of your code, like objects and classes, while your program is running.

In JavaScript, you were already able to do some reflection operations using the Object. But now, there’s a proper Reflection API available in JavaScript as well.

The Reflect object comes with a set of methods that let you create and update object instances. Unlike Math and JSON, Reflect doesn’t have a constructor, so you can’t create a new instance of it using the new operator, and you also can’t call it as a function.

However, Reflect has its own version of the new operator called Reflect.construct(). Here’s how you use it:

Reflect.construct(target, argumentsList[, newTarget])

When we talk about the target and newTarget arguments, we’re referring to objects that have their own constructors. In simpler terms, these arguments are objects that have the ability to create new instances of themselves.

var dt = Reflect.construct(Date, [2017, 0 , 1]); console.log(dt); // Sun Jan 01 2017 00:00:00 GMT+0100

This code accomplishes the same thing as using the new operator to instantiate a Date. However, there are some benefits to using Reflection, which is a standard in the ECMAScript 6 language. One advantage is that you can take advantage of the newTarget argument.

The value of the newTarget’s prototype (specifically, the prototype of the newTarget’s constructor) becomes the prototype of the newly created instance.

A prototype is an object’s property, and its value is also an object that carries the properties of the original object. In other words, an object inherits its members from its prototype.

Let me show you an example:

“`javascript

class A {

constructor() {

this.message = function() {

console.log(‘message from A’);

}

}

}

class B {

constructor() {

this.message();

}

data() {

console.log(‘data from B’);

}

}

const obj = Reflect.construct(A, [], B);

console.log(obj.message()); // message from A

console.log(obj.data()); // data from B

console.log(obj instanceof B); // true

“`

By passing B as the third argument to Reflect.construct(), the prototype value of the obj object is set to be the same as the prototype of B’s constructor, which includes the properties message and data.

So, I’m trying to understand something here. How can this “obj” access both the message and data available at its prototype? It’s because “obj” is made using “A” and it has its own message that it received from “A”.

Now, “obj” may look like an array, but it’s not really an instance of the Array. That’s because its prototype is actually set to Object.

obj = Reflect.construct(Array, [1,2,3], Object)

console.log(obj) // Array [ 1, 2, 3 ]

console.log(obj instanceof Array) // false

This Reflect.construct() is actually pretty helpful when you want to create an object using more than one blueprint.

3. The Object.create() method

Here’s another way to create a new ordinary object with a specific prototype: Object.create(). It may seem similar to using the new operator, but trust me, it’s not the same.

The Object.create(O[, propertiesObject]) method allows me to create a new object using an existing object as its prototype. I can also add additional properties to the newly created object if I want.

Here’s an example to demonstrate how it works:

class A {

constructor() {

console.log(‘message from A’);

}

}

var obj = Object.create(new A(), {

data: {

writable: true,

configurable: true,

value: function() {

console.log(‘data from obj’);

}

}

});

console.log(obj.message()); // message from A

console.log(obj.data()); // data from obj

var obj1 = Object.create(new A(), {

foo: {

writable: true,

configurable: true,

value: function() {

console.log(‘foo from obj1’);

}

}

});

console.log(obj1.message()); // message from A

console.log(obj1.foo()); // foo from obj1

By using the Object.create() method, I can create new objects that inherit properties and behavior from an existing object. This allows for flexible and efficient object creation in JavaScript.

When we talk about the obj object, I added a property called data to it. In the obj1 object, I added a property called foo. So, you can see that we can add properties and methods to a new object.

This is really useful when you want to create many objects that are similar in some ways but have different additional properties or methods. Using the Object.create() syntax saves you the trouble of having to write each one separately.

This is really useful when you want to create many objects that are similar in some ways but have different additional properties or methods. Using the Object.create() syntax saves you the trouble of having to write each one separately.