0

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
}
1
  • 1
    Will init code even be run in the first case? It looks like you are not calling that function(whatever that is). It's not a conventional 'constructor' as is normally done in javascript. Commented Jun 19, 2009 at 7:04

2 Answers 2

3

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;
}
Sign up to request clarification or add additional context in comments.

Comments

3

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.

2 Comments

Don't use instances for prototype inheritance. Do use Object.create if available
A object's prototype has to be an instance.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.