mercredi 23 novembre 2022

Why do you have to define functions under a constructor's prototype but not when using other design patterns?

I am having trouble understanding prototypal inheritance when using constructors. I reached this lesson in The Odin Project where it says:

If you’re using constructors to make your objects it is best to define functions on the prototype of that object. Doing so means that a single instance of each function will be shared between all of the Student objects. If we declare the function directly in the constructor, like we did when they were first introduced, that function would be duplicated every time a new Student is created.

function Student() {
}

Student.prototype.sayName = function() {
  console.log(this.name)
}

I understand why you wouldn't want to duplicate the functions for every instance of the object, but I don't understand two things:

  1. Does this also apply to Classes which have constructors and Object() constructors?

  2. Why isn't this needed on other design patterns like Factory functions or the Module pattern? Wouldn't those functions also be duplicated for every instance of the object?

Aucun commentaire:

Enregistrer un commentaire