Ways of creating a js class

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.

I would say you should probably use the class keyword as it is newer, and it just makes things more apparent

2 Likes

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.

1 Like

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.

Good to know. I will read up on all that. I have just started really.

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.

You may find these of use:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Details_of_the_Object_Model

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.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.