0

I am creating a JavaScript constructor. Consider this example:

function Student(name)
{
    this.name = name;
}

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

var s = new Student("Eden");
s.printName();

This above code works all well. But I can write the same this way also:

function Student(name)
{
    this.name = name;

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

var s = new Student("Eden");
s.printName();

I feel the second method is correct way because printName should be own property of new object not an inherited property. Adding to prototype makes it an inherited property.

Why do developer prefer the first method?

Narayan Prusty
  • 397
  • 3
  • 9

1 Answers1

2

By attaching functions directly to this in a constructor, that means every instance of Student has it's own copy of printName. That isn't very efficient. By attaching it to the prototype chain of Student, there is only one copy of the printName function and any instance of Student has it in it's prototype chain.

While there are other differences in those two approaches for attaching function to objects, that is the simplest and easiest to remember.

If you want the full dictionary of reasons how the two differ, please refer to this answer to an extremely similar question.

Community
  • 1
  • 1
arb
  • 7,753
  • 7
  • 31
  • 66
  • This is true. Try to think of properties add to the prototype as static. They are the same for all instances. If you add them to 'this' you are creating multiple functions that all do the exact same thing. – endy Jul 07 '15 at 15:56