Constructor functions in javascript
Constructor functions are functions that are used to construct new objects. The new
operator is used to create new instances based off a constructor function. There are some built-in JavaScript constructors, such as new Array()
and new Date()
, but we can also create our own custom templates from which to build new objects.
To begin, a constructor function is just a regular function. It becomes a constructor when it is called on by an instance with the new
keyword. In JavaScript, we capitalize the first letter of a constructor function by convention.
function Hero(name, level) {
this.name = name;
this.level = level;
}
The this
keyword will refer to the new instance that is created, so setting this.name
to the name
parameter ensures the new object will have a name
property set.
Now we can create a new instance with new
.
let hero1 = new Hero('Bjorn', 1);
Now if we get the [[Prototype]]
of hero1
, we will be able to see the constructor
as Hero()
. (Remember, this has the same input as hero1.__proto__
, but is the proper method to use.)
Object.getPrototypeOf(hero1);
// Output
constructor: ƒ Hero(name, level)