Yes there are many ways to create and use objects. So why/when is it better to create a constructor versus declare a class and use the constructor() method? My instructor said it doesn't make a difference but I don't believe him.
// 1
function Grumpy(name, profile, power){
this.name = name;
this.profile = profile;
this.power = power;
}
Versus
// 2
class Grumpy{
constructor(name, profile, power){
this.name = name;
this.profile = profile;
this.power = power;
}
}
JavaScript still follows a prototype-based inheritance model. Classes in JavaScript are syntactic sugar over the prototype-based inheritance model which we use to implement OOP concepts. Thus the introduction of classes in JS made it easier for developers to build software around OOP concepts.
A class is a constructor technically. Any object with a [[ Construct ]] internal method is considered one. All constructors are functions, but not all functions are constructors. Functions in Javascript can be of many kinds.
A constructor is a special function that creates and initializes an object instance of a class. In JavaScript, a constructor gets called when an object is created using the new keyword. The purpose of a constructor is to create a new object and set values for any existing object properties.
Definition and Usage Note: A class cannot have more than one constructor() method. This will throw a SyntaxError .
JavaScript classes, introduced in ECMAScript 2015, are primarily syntactical sugar over JavaScript's existing prototype-based inheritance. The class syntax does not introduce a new object-oriented inheritance model to JavaScript.
For more defailts, see MDN
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With