Reputation: 113976
What's the advantage of using a constructor function like so:
var MyLibrary = new function(){
var self = this;
self.MyLibrary = function(){
// init code
}
}
Instead of simply writing code inside the object?
var MyLibrary = new function(){
// init code
}
Upvotes: 0
Views: 1483
Reputation: 28240
Neither of those are quite right, although the second one might work, but isn't really an object, more like a singleton(but in a weird way). Here's an example of a class with a constructor:
// Class & Constructor definition
function Rectangle(w,h) {
this.width = w;
this.height = h;
}
// Now your class methods go on the prototype object
Rectangle.prototype.area = function() {
return this.width * this.height;
}
Now to use this class:
var myRect = new Rectangle(3,4);
myRect.area();
You can also define a class by saving the 'constructor' to a var using anonymous functions instead of named functions:
// Class & Constructor definition
var Rectangle = function(w,h) {
this.width = w;
this.height = h;
}
// Now your class methods go on the prototype object
Rectangle.prototype.area = function() {
return this.width * this.height;
}
Upvotes: 3
Reputation: 90493
Well, if you're using prototype inheritance to create new classes, you'll do something like this:
function MyBaseClass() {
// common stuff here
}
function MySubClass() {
// subclass-specific stuff here
}
MySubClass.prototype = new MyBaseClass();
That last line is required to establish the inheritance chain. However, it also has the side-effect of executing the body of MyBaseClass
, which might cause problems (particularly if the MyBaseClass
function is expecting arguments).
If you don't want that to happen, do something like this:
function MyBaseClass() {
this.init = function() {
// initialisation stuff here
}
// common stuff here
}
function MySubClass() {
// subclass-specific stuff here
this.init();
}
MySubClass.prototype = new MyBaseClass();
The initialisation code in init
is now only executed when you create an instance of MySubClass
.
Upvotes: 3