0

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");
      }
}
2
  • The constructor is useful to apply Dependency Injection and with that design you could do tests easy Commented Aug 17, 2019 at 1:06
  • It's not different from a "constructor function". In fact, it is the constructor function Cat itself. It is not a method. Commented Nov 12, 2019 at 19:17

4 Answers 4

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0

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
}

Comments

0

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.

2 Comments

"".constructor(2) === 2 //false
My bad, forgot quotes around the 2 Meant to say the "".constructor(2) and String(2) both make "2" as I mentioned above

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.