Reputation: 313
Can you please recommend which of the following is the best or their pros and cons? I am not sure, but maybe, it depends on the type of use ? Is one heavier than the other in terms of performance (keeping the class in memory etc.) ?
Thanks in advance!
Method 1
var MyClass = function(something) {
this.something = something;
}
MyClass.prototype = {
myMethod: function(arg) {
this.arg = arg;
return this.arg;
},
mySecondMethod: function() {
return "helloWorld";
}
}
Method 2
var MyClass = (function () {
function MyClass(something) {
this.something = something;
}
MyClass.prototype.myMethod = function (arg) {
this.arg = arg;
return this.arg;
};
MyClass.prototype.mySecondMethod = function (arg) {
return "helloWorld";
}
return MyClass;
})();
Upvotes: 0
Views: 214
Reputation: 71918
There are two main differences:
In the first method, you are replacing the default prototype with an entirely new object. That's okay, but instances of MyClass will then inherit the wrong constructor
property. You can fix that with:
MyClass.prototype = {
constructor: MyClass
myMethod: // etc...
Or simply extend the default prototype:
var MyClass = function(something) {
this.something = something;
}
MyClass.prototype.myMethod = function(arg) {
this.arg = arg;
return this.arg;
}
In the second method, you wrapped the whole thing in an immediately-invoked function. This is useful if you want to have "private" (actually, private-like) variables, as variables declared inside will be visible by functions declared inside, but won't leak to the outer scope:
var MyClass = (function () {
var privateVar = "something"; // this will be visible by the functions
// below but not outside
function MyClass(something) {
this.something = something;
}
MyClass.prototype.myMethod = function (arg) {
this.arg = arg;
return this.arg;
};
// You were missing this
return MyClass;
})();
These are the differences. Both ultimately do the same thing: create a constructor, with some properties/methods attached to the prototype. There's no difference in terms of "optimization".
Upvotes: 3