Reputation: 25768
Using this
var Class1 = function() {
this.test1 = function() {
};
};
and the following
function Class1() {
};
Class1.prototype.test1 = function() {
};
Is there difference between those two?
Upvotes: 2
Views: 85
Reputation: 2121
Using the later one in efficient.
Functions in JavaScript are objects. Every object in JavaScript holds a hidden piece of state – a reference to another object known as the object’s prototype.
Using prototype multiple objects can maintain references to the same prototype object.
This is a great reference to know how prototype in js works.
Upvotes: 0
Reputation: 665122
Yes, there are. See
for the two (independent) differences.
Upvotes: 0
Reputation: 382831
There is difference which affects performance as well.
The first one will add function to each instance of the created class while latter won't. For the latter method, JavaScript will look into prototype
chain of the object and would return the needed method, the test1
in your case.
Upvotes: 0
Reputation: 887867
The first one makes a separate copy of the function for each class instance.
It also allows the function to use closure'd variables from the constructor.
Upvotes: 3