Constructors in JavaScript
Constructors
82
In JavaScript, constructors are special functions that are used to create objects. They help define the structure and behavior of an object. A constructor function is called when a new object is created with the keyword new
.
Here's an example of a constructor function:
function Person(name, age) { this.name = name; this.age = age; } var john = new Person("John", 25);
In this example, Person
is a constructor function that takes two parameters, name
and age
. The this
keyword refers to the object being created and sets the name
and age
properties of that object.
When we call new Person("John", 25)
, JavaScript creates a new object and assigns it to the john
variable. The Person
constructor is called with the arguments "John"
and 25
, and the name
and age
properties of the john
object are set accordingly.
Constructors can also define methods for the objects they create.
Here's an example:
function Person(name, age) { this.name = name; this.age = age; this.sayHello = function() { console.log("Hello, my name is " + this.name); } } var john = new Person("John", 25); john.sayHello(); // prints "Hello, my name is John"
In this example, we've added a sayHello
method to the Person
constructor. This method is defined inside the constructor function and is called like any other method on the object.
Constructors are a powerful tool in JavaScript because they allow us to create complex objects with behavior that's specific to the object's purpose.
March 25, 2023