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
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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With