javascriptdesign-patternsconstructorprototypal-inheritance

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?


Solution

  • Several people replied to my question but did not provide any answers. In order to close this question as answered, I compiled the information they provided here.

    Classes:: Class syntax methods are automatically added to the prototype.

    Object() constructor: Is not used to define objects with methods.

    Module Pattern: The module pattern does not have multiple instances, so there is no instances to duplicate the functions.

    Factory Functions: Are affected by this issue but there are ways to mitigate this. Check out the replies from Bergi which detail a few ways to mitigate it.