javascript - Why we use "prototype" property to add methods to constructor instances? -


this question has answer here:

i creating javascript constructor. consider 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 well. can write same way also:

function student(name) {     this.name = name;      this.printname = function(){         console.log(this.name);     } }  var s = new student("eden"); s.printname(); 

i feel second method correct way because printname should own property of new object not inherited property. adding prototype makes inherited property.

why developer prefer first method?

by attaching functions directly this in constructor, means every instance of student has it's own copy of printname. isn't efficient. attaching prototype chain of student, there 1 copy of printname function , instance of student has in it's prototype chain.

while there other differences in 2 approaches attaching function objects, simplest , easiest remember.

if want full dictionary of reasons how 2 differ, please refer this answer extremely similar question.


Comments

Popular posts from this blog

How to provide Authorization & Authentication using Asp.net, C#? -

toolbar - How to add link to user registration inside toobar in admin joomla 3 custom component -

android - Pass an Serializable object in AIDL -