0

When defining javascript objects that behave like classes that have state and functions that manipulate that state is it better to define functions when defining the object like so:

function MyNewClass(){
   //State
   this.value = ""
   this.otherValue = ""
   //Functions
   this.someFunction = function(){
      //Some logic here
   }
}

Or it it better practice to define functions on the prototype of the object such as:

function MyNewClass (){
   //state
   this.value = ""
   this.otherValue = ""
}

MyNewClass.prototype.someFunction = function(){
  //Some logic here
}

Are there any advantages to defining object functions on the prototype? Thanks!

Zenith
  • 209
  • 3
  • 13

3 Answers3

1

Because functions are objects, given the described scenario, we have two behavior:

  • If you declare the function on the "class" function, every object you create then it will have a copy of that function (object), so the memory usage will increase.

  • However, if you add the function to the prototype, the function will be shared by all the objects, so there will be a save of memory

Rafa Romero
  • 2,667
  • 5
  • 25
  • 51
0

functions of the object should be declared using prototype because prototype is a common space that is shared by all the objects created by the same constructor function and it also saves memory because all objects do not have there own functions created but they all are pointing to one common place. you can refer it here https://www.youtube.com/watch?v=fBpPfPjxOhc&list=PLqq-6Pq4lTTaflXUL0v3TSm86nodn0c_u example

enter code here

//constructor function

function gh(){
this.x=1;
}
//now if you create a object 
var p=new gh();
//now i need function show in my object p
function show(){
console.log(x);
}
gh.prototype.show=show();

//it will be added all objects automatically (to understand this study scope chain)

0

You can see the difference for yourself by running this code:

var output = function(s) { document.getElementById("output").innerText += s; }

function MyNewClass() {
   this.foo = function() {
      output("1");
   }
}

MyNewClass.prototype.bar = function(){
      output("2");
};
var a = new MyNewClass();
a.foo();
a.bar();


a.foo = function() { output("3") };
MyNewClass.prototype.bar = function() { output("4"); };

a.foo();
a.bar();

var b = new MyNewClass();
b.foo();
b.bar();

The output is: 123414

When you change a function as a member variable, you only change that instance. If you change it in the prototype, it affects all instances.

John Wu
  • 50,556
  • 8
  • 44
  • 80