Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript object instance vs returned functions

What are the differences in creating objects in javascript between

test = function(a, b){
   this.calculate = function(){
      return a + b;
   }
}
obj = new test(1, 2);
console.log(obj.calculate());

And

test = function(a, b){
   return {
      calculate: function(){
         return a + b;
      }
   }
}
obj = test(1, 2);
console.log(obj.calculate());

I have used both in different situations but never understood the difference, I know that the latter approach has the over head of creating the functions for ever instance but still see it used in a lot of situations, can anyone clarafy this for me? I was unable to find anything about this by searching

like image 352
Jye Lewis Avatar asked Jan 23 '13 09:01

Jye Lewis


2 Answers

The first one also creates the functions for every instance. The only differences in this situation is that the new instance inherits from test.prototype in the first case, while it directly inherits from Object in the second case.

In the first case it would be easier to let the instances share code, by adding the functions to the prototype. For example:

var Test = function(a, b){
   this._a = a;
   this._b = b;
};

Test.prototype.calculate = function(){
   return this._a + this._b;
};

Since all instances inherit from Test.prototype, the calculate function exists only once and all instances refer to the same function.

like image 110
Felix Kling Avatar answered Sep 22 '22 12:09

Felix Kling


As Felix said in the comment, the difference is the inheritance chain. The first inherits from test.prototype and the second from Object. The consequence is that if you wanted to create the function only once and make every instance share it, you'd have to do something like this:

test = function (a, b) {
  this.a = a;
  this.b = b;
}

test.prototype.calculate = function () {
  return this.a + this.b;
}
like image 33
Alex Ciminian Avatar answered Sep 21 '22 12:09

Alex Ciminian