Constructors in Javascript, Back to basics (BTB) ๐Ÿฆ…

Constructors in Javascript, Back to basics (BTB) ๐Ÿฆ…

ยท

2 min read

In JavaScript, a constructor is a function that is used to create and initialize objects. When a constructor is called with the "new" keyword, it creates a new object and sets the "this" keyword to reference that object. The constructor can then set properties and methods on the object using the "this" keyword, and can return the object.

Here is an example of a simple constructor function in JavaScript:

javascriptCopy codefunction Person(name, age) {
  this.name = name;
  this.age = age;
}

var person1 = new Person("Alice", 25);
var person2 = new Person("Bob", 30);

In this example, the Person function serves as a constructor for creating Person objects. When called with the "new" keyword, it creates a new object and sets the "name" and "age" properties on the object using the "this" keyword. The resulting object is then returned.

You can add methods to a constructor function by attaching them to the prototype property of the constructor function. For example:

javascriptCopy codefunction Person(name, age) {
  this.name = name;
  this.age = age;
}

Person.prototype.sayHello = function() {
  console.log("Hello, my name is " + this.name);
};

var person1 = new Person("Alice", 25);
person1.sayHello(); // "Hello, my name is Alice"

In this example, the "sayHello" method is added to the prototype property of the Person constructor function, which means that all Person objects will have access to this method. When called on a Person object, it will print out a greeting with the person's name.

Did you find this article valuable?

Support Shippi ๐Ÿ„ by becoming a sponsor. Any amount is appreciated!

ย