Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do we add methods using the prototype property of the constructor function?

One thing I don't understand with prototypes and constructor functions..

Say I have this constructor function that will create an object with a 'name' property and a 'logName' method

function MyExample(param1){
  this.name = param1;
};

MyExample.prototype.logName = function(){
  console.log(this.name);
}

I understand I just added a method (logName) to the constructor function's (myExample) prototype..so that when I create a new object (me) using this constructor function that object will inherit the 'name' property and the 'logName' method. The logName method will be part of new object's (me) proto property

var me = new MyExample('bob');
me.logName(); //bob

..But why not just add the logName method to the object the constructor function is creating? (not the prototype of the constructor function) Wouldn't that provide the same result? Even though 'logName' will not be part of the new object's proto property.

function MyExample(param1){
   this.name = param1;
   this.logName = function(){
      console.log(this.name)
   };
};

var me = new MyExample('bob');
me.logName(); //bob
like image 324
NewToJS Avatar asked Dec 14 '22 02:12

NewToJS


1 Answers

In your second example you recreate the logName function every time you create a new instance of MyExample. If you use the MyExample's prototype then one logName method is shared across all instances of the MyExample object and context is passed around automatically.

The prototype also allows you to add a new method at a later point that can be accessed by already-existing objects of that type or globally modify a method for all objects of a type.

This question touches on the same topic if you would like more information, Advantages of using prototype, vs defining methods straight in the constructor?

like image 135
Marie Avatar answered Dec 17 '22 01:12

Marie