1

What's the difference between the following snippets of code?

function Student(name, grade) {
  this.name = name
  this.grade = grade
}

Student.prototype.sayName = function() {
  console.log(this.name)
}
Student.prototype.goToProm = function() {
  console.log("Eh.. go to prom?")
}
function Student(name, grade) {
  this.name = name
  this.grade = grade

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

  this.goToProm = function() {
      console.log("Eh.. go to prom?")
  }
}

Apparently the first way is better:

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. In this example, that wouldn’t really matter much, but in a project that is creating thousands of objects, it really can make a difference.

Can someone explain this a bit more?

As far as I understand if we add it to the prototype(parent) of Student when we create new objects they will only be created with name and grade instead of each object allocating more data on the heap to hold the function definitions for sayName and goToProm and then they can utilise the functions which are defined in the parent of Student.

Is this the reason why?

CupOfGreenTea
  • 399
  • 1
  • 4
  • 12
  • _"Apparently the second way is better"_... according to whom? Also it's saying that the **first way** is better – Phil Feb 16 '22 at 03:45
  • @Phil https://www.theodinproject.com/paths/full-stack-javascript/courses/javascript/lessons/objects-and-object-constructors – CupOfGreenTea Feb 16 '22 at 03:47

0 Answers0