Highlighted brick wall with neon inscription constructor

Constructor Functions

In traditional OO languages, constructor functions are a normal part of the code. Constructor functions are denoted by a capital letter by practice. Constructor functions look like “regular functions, but behave differently. Here is an example…

function Animal(name){
    this.animalName = name;
}
let gorilla = new Animal(‘Bongo’); 

Notice the capital “A”. That is a JavaScript constructor function convention. Also, notice we are using the “new” keyword. This instantiates the new object based upon the constructor function. We can even pass information to it like we are doing here. What about constructor function methods?

function Animal(name){
    this.animalName = name;
    this.grunt = function(){
        console.log(‘ugh!’);
    };
}
let gorilla = new Animal(‘Bongo’); gorilla.grunt();

The output will be “ugh!”.

Happy Coding!

Clay Hess

Share this post

Share on facebook
Share on google
Share on twitter
Share on linkedin
Share on pinterest
Share on print
Share on email
Skip to content