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?