1

why should i use prototypes is js?

for example if i want to create a constructor like:

var Person = function(name, yearOfBirth){
    this.name = name;
    this.yearOfBirth = yearOfBirth;
    this.calculateAge = function(){
        console.log(2018-this.yearOfBirth);
    }
}

is better to use prototype for functions like:

var Person = function(name, yearOfBirth){
    this.name = name;
    this.yearOfBirth = yearOfBirth;
}


Person.prototype.calculateAge  = function(){
    console.log(2018-this.yearOfBirth);
}

should i use prototype also for props like name etc?

Can someone tell me the differences between using or not prototypes and what's the best use of it?

Thanks

EDIT: this is the best answer that i've found: https://hackernoon.com/prototypes-in-javascript-5bba2990e04b

claud.io
  • 1,523
  • 3
  • 15
  • 30

1 Answers1

1

Prototype properties are shared across all instances of the constructor function.

In your case the calculateAge function need not be required as a separate instance for all objects that you create out of Person and hence can be moved to Prototype, whereas properties like name and yearOfBirth need a separate instance for each object that you create from Person

You can define Prototypes properties on constructor functions when you wish to create a common property shared across all instances of the function.

Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400