Hi. I have seen two way of creating a class that we can later instantiate as objects but they are different. I was wondering which one I am supposed to use.
//W3 schools
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
this.updateAge = function () {
this.age++;
};
}
// Another tutorial
function Person (name, age){
this.name = name;
this.age = age;
this.updateAge = function () {
this.age++;
};
}
These are both functionally the same. Under the hood, class as you have it actually converts to function, as you have it.
The class keyword is a fairly new addition to the language, both to ease those coming from class-based languages and to streamline insurance in javascript.
So yes, these are both constructor functions, exactly the same internally.
Wow that was fast. It looks like I’m going to love this forum. I come from c sharp so it’s a little weird no to have to use type anywhere.
Cheers guys.
The real downside to the class keyword is, it’s not really. Javascript doesn’t do classes per se, it does prototypes. Javascript doesn’t do inheritance, it does prototype delegation. They’re small gotchas, but issuing class in javascript tends to trip folks up, because they think “class like in C”… And it’s not.
Prototype delegation is the technically right term to use when talking about how a JavaScript object gets its inheritance, but you’ll often see the word inheritance used, and if you do see prototype delegation as a term it is often being used interchangeably.
Well aware of all three, and very valuable resources. My point stands: using a class because it’s a class can lead to a false sense of security. I’m not saying don’t use it, I’m saying be aware what it is, and its consequences.