Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

188
Views
Difference between function defined inside object constructor versus on the prototype

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?

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!