Javascript object object and return 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 used both in different situations, but I never understood the difference, I know that the last approach has overhead creation of functions for an ever instance, but still sees that it is used in many situations, can someone do this for me ? I could not find anything about it by doing a search

+6
source share
2 answers

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

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

 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.

+5
source

As Felix noted in the commentary, the difference lies in the inheritance chain. The first inherits from test.prototype , and the second from Object . The consequence of this is that if you want to create a function only once and make each instance of it shared, you need to do something like this:

 test = function (a, b) { this.a = a; this.b = b; } test.prototype.calculate = function () { return this.a + this.b; } 
+2
source

All Articles