javascript - Why we use "prototype" property to add methods to constructor instances? -
this question has answer here:
- use of 'prototype' vs. 'this' in javascript? 13 answers
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
Post a Comment