How to Create Objects and Constructors in Object-Oriented JavaScript?

Estimated read time 1 min read

In Object-Oriented JavaScript, you can create objects using the object literal syntax or using constructors.

  1. Object literal syntax: This is a simple and straightforward way to create an object. You use curly braces {} to define the object and its properties.
const person = {
  name: 'John',
  age: 30
};
  1. Constructors: Constructors are functions that are used to create objects. You can use the new operator to create an object using a constructor.
function Person(name, age) {
  this.name = name;
  this.age = age;
}

const person = new Person('John', 30);

The this keyword in the constructor refers to the new object that is being created. The properties and methods of the object can be defined using the this keyword.

Here is an example of creating objects using both the object literal syntax and a constructor:

// Object literal syntax
const person = {
  name: 'John',
  age: 30
};

// Constructor
function Person(name, age) {
  this.name = name;
  this.age = age;
}

const person = new Person('John', 30);

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply