JavaScriptTutorials

JavaScript – Constructor Functions

What are Constructor functions in JavaScript? Why are they useful? This post will hopefully answer these questions.

In JavaScript, constructors are a way to create a class which can be instantiated into usable objects. Similar to JavaScript prototypes.

Let’s create a constructor Animal which can be instantiated into various different animals such as dogs, cats, lions, etc. We will take in three arguments to define our animal objects – color (string), sound it makes (string), and it’s weight (integer):

function Animal(c, s, w) {
let color = c;
let sound = s;
let weight = w;

// setters
this.setFurColor = c => color = c;
this.setSound = s => sound = s;
this.setWeight = w => weight = w;

// getters
this.getFurColor = () => color;
this.getSound = () => sound;
this.getWeight = () => weight;

// public methods
this.speak = () => console.log(sound);
}

As you can see, we are creating three private variables to hold our animal characteristics, color, sound, and weight, and then we’re exposing 6 public mutator methods to get/set each of these characteristics. This way we prevent direct manipulation of the animal characteristics. We also have a public method “speak” which will print the animal’s sound to the console.

Also notice how the constructor function starts with a capital letter. This is a common convention with JavaScript constructors that you should follow. It will still work just as expected if we named it “animal()” instead, but conventions are important.

Let’s instantiate a few animal objects to see how this works:

let cat = new Animal('black', 'meow', 10);
let dog = new Animal('white', 'ruff!', 60);
let lion = new Animal('tan', 'rawr!', 175);
let lionCub = new Animal('tan', 'reow!', 12);

cat.speak(); // "meow"
dog.speak(); // "ruff!"
lion.speak(); // "rawr!"
lionCub.speak(); // "reow!"

// change the cat's color to yellow
console.log(cat.getFurColor()); // "black"

cat.setFurColor('yellow');

console.log(cat.getFurColor()); // "yellow"

// print the lion's weight
console.log(lion.getWeight()); // 175

I hope this helps, and at least makes some sense. You can see a pen of it here.

Please, as always, also educate me on better ways to code in the comments.

Leave a Reply

Your email address will not be published. Required fields are marked *