Currently I am working in a project where we are writing Object Oriented JavaScript. In this project I have seen two different ways of defining a class:
1: Declare functions at once on the prototype
My.Namespace.ClassName = function(param1, param2) {
this.member1 = param1;
this.member2 = param2;
};
My.Namespace.ClassName.prototype = {
myFunction1: function() {
return this.member1 + " " + this.member2;
},
myFunction2: function(param1) {
this.member3 = paraml;
}
};
2:Prepare each function individual on the prototype
My.Namespace.ClassName = function(param1, param2) {
this.member1 = param1;
this.member2 = param2;
};
My.Namespace.ClassName.prototype.myFunction1 = function() {
return this.member1 + " " + this.member2;
};
My.Namespace.ClassName.prototype.myFunction2 = function(param1) {
this.member3 = paraml;
};
Is there any difference in how JavaScript behaves based on the two given examples or is it only a style difference?
Personally I haven't seen any behavior difference but I have the feeling that there must be a subtle difference which I am currently missing.
Besides that. I would like to know whether this is a common practice or are there much better ways to define classes.