when to use constructors in javascript code example
Example 1: constructors javascript
function Bird() {
this.name = "Albert";
this.color = "blue";
this.numLegs = 2;
}
/*
This constructor defines a Bird object with properties name, color, and
numLegs set to Albert, blue, and 2, respectively.
Constructors follow a few conventions:
-Constructors are defined with a capitalized name to distinguish them from
other functions that are not constructors.
-Constructors use the keyword this to set properties of the object they will
create. Inside the constructor, this refers to the new object it will create.
-Constructors define properties and behaviors instead of returning a value as
other functions might.
*/
Example 2: how to create a constructor in javascript
function Bird() {
this.name = "Albert";
this.color = "blue";
this.numLegs = 2;
}
let blueBird = new Bird();