MistyD
MistyD

Reputation: 17223

What is the purpose of "constructor" method in javascript?

This link states we can create a constructor using a constructor method. I wanted to know when would I use that and how is it different from constructor functions. From what I understand is. A regular function is a constructor function when its called with new. What role does "constructor" keyword play in this example

class Cat {

      constructor(name,color){
          this.name = name;
          this.color = color;
      }

      speak(){
          console.log("Meow");
      }
}

Upvotes: 0

Views: 126

Answers (4)

ceckenrode
ceckenrode

Reputation: 4703

Every object prototype in JavaScript comes with a constructor method. The constructor method is the constructor function used to create the object.

For instance, we can turn a number into a string using the String constructor

String(2) === "2";

we can also do

"".constructor(2) === "2"

This works the same because the string's "constructor" points to the String constructor function.

Classes in JavaScript aren't classes as they exist in languages like Java or Ruby since JavaScript uses a prototypal inheritance system. So classes in JavaScript are just sugar syntax for plain constructor functions. This allows developers to take advantage of some OOP features of JavaScript without needing to know about many of the nuances about how its inheritance system works.

So the following:

function Cat (name,color){
     this.name = name;
     this.color = color;
 }

Cat.prototype.speak = function(){
  console.log("Meow");
}

Is effectively the same as

class Cat {
 constructor(name,color){
     this.name = name;
     this.color = color;
 }

 speak(){
     console.log("Meow");
 }
}

Both can be instantiated using the new keyword

new Cat("Mittens", "black");

The "constructor" as described in the class example points to the underlying JavaScript constructor function. Remember that "class" in JavaScript is just a friendly wrapper around a constructor function that makes using it more similar to using classes in other languages.

When working with a class you'd use the "constructor" method to set some values directly to the object that will be created, rather than on its prototype. The prototype is an object common to all objects created with a class/constructor, that's used to share functionality between them.

Upvotes: 0

traktor
traktor

Reputation: 19301

The constructor method within a class declaration/expression is required as part of the syntax. It supplies the code to execute when "creating" a new instance of the class. Here "creating" and "constructing" mean the same thing in JavaScript.

The constructor method of the class creates a constructor function object that is the value of the class declaration:

class myClass {
    constructor() {
        this.bar = "foo";
    }
    moreInfo() {
        console.log( "myClass is the same as its constructor method = " 
        + (myClass === this.constructor)); 
    }
}
    
// what is myClass?
console.log( new myClass().moreInfo());

So, long story short, class declarations create a constructor function of the same name.

Going back to basic JS, all standard functions (that are not either arrow functions or class declarations or expressions) can be used as constructor functions by design: just because you never use them as a consctructor doesn't mean you couldn't. Of course, the sense of using a particular function as a constructor does depend on whether it was written for the purpose of constructing objects:

function add( a, b) {  // Not written as a constructor
    return a+b;
} 
function record( a, b) { // written as a constructor
    this.a = a;
    this.b = b
}

Upvotes: 0

Federkun
Federkun

Reputation: 36944

Do not forget that there's no real class in javascript. If you try to transpile your class, you will get something similar to:

var Cat = function () {
  function Cat(name, color) {
    this.name = name;
    this.color = color;
  }

  Cat.prototype.speak = function speak() {
    console.log("Meow");
  };

  return Cat;
}();

No surprise, the constructor is a constructor function.

Upvotes: 0

Phix
Phix

Reputation: 9890

When instantiating a new instance of this class with new Cat(), you'd pass in the name and color of the cat in the order defined by the constructor arguments. You'll then have a new instance of Cat with the name and color properties defined.

const spot = new Cat('Spot', 'Orange')

That will create a new cat with a name of "Spot" and a color of "Orange". It's just a reserved keyword that is executed when a new instance is created.

It's similar to the ES5 syntax, just with some syntactic sugar:

function Cat(name, color) {
  this.name = name;
  this.color = color
}

Cat.prototype.speak = function() {
  console.log('Meow')
}

const c = new Cat('Spot', 'Orange')
c.speak() // Meow
console.log(c.name, c.color) // Spot Orange

You can read more on MDN

Upvotes: 1

Related Questions