Home > Mobile >  difference between constructor and class in javascript
difference between constructor and class in javascript

Time:02-24

what is the const halley=... referring to?Is it storing the new created object?or is itself a new object?and what does the Dog after the new keyword means?Class or constructor?

class Dog {
 constructor(name) {
   this.name = name;
   this.behavior = 0;
 } 
}

const halley = new Dog('Halley'); // Create new Dog instance
console.log(halley.name);

CodePudding user response:

In JavaScript, a constructor function is a function designed for use with the new keyword to create instances of a type of object. Typically you would assign something to its prototype property to define properties that would be inherited by the instance.

The class keyword is a newish feature that allows the creation of a constructor function and its associated prototype using syntax which looks more like traditional OO syntax in other programming languages.

The value assigned to Dog is both a class and a constructor function.

CodePudding user response:

This part define the class. A class is like a recipe to make objects. A constructor is a method of a class that define how to create new instances (objects):

class Dog {
 constructor(name) {
   this.name = name;
   this.behavior = 0;
 } 
}

This part create an instance (object) of the class Dog:

const halley = new Dog('Halley');
  • Related