I have been learning self-taught JavaScript for a while now and I just started refactoring a canvas game I made, and I thought to check if my way of writing classes was 'correct' and I stumbled upon a new way to write them.
So my question is which of the following is the best way to create objects in JavaScript, and if they are all virtually the same which one is more widely accepted, or when is it appropriate to use each one.
Class declaration:
This is the one that I did not know was available in JS.
class Person {
constructor(name) {
this.name = name;
}
}
let Me = new Person("John");
Object literal:
From what I can tell this is good for one-off objects.
let Me = {
type: "Person",
name: "John";
};
Function Object:
I don't know if this is the proper name but I don't know what else to call it.
function Person(name) {
this.name = name;
this.sayName = function() {
return "Hi, my name is " + this.name;
};
}
let me = new Person("John");
Prototypes:
From what I can tell they are used for adding extra functionality to preexisting objects (i.e. a value mapping function that works on the defualt JS number objects)
function Person(name) {
this.name = name;
}
Person.prototype.sayName = function() {
return "Hi, my name is " + this.name;
};
let me = new Person("John");