How to implement multiple new functions in Javascript object?

I am doing some reading about class creation in Javascript. I know the concept does not exist in Javascript and that one can work with prototype.

I am trying to translate the following piece of code from Java to Javascript. Specifically, I want to have two constructors, one parameterless and one with two parameters:

public class MyClass {

    int width = 10;
    int height = 20;

    public MyClass() { };

    public MyClass(int w, int h) {

        this.width = w;
        this.height = h;

    };

    ...

}

As far as I understand, I need to define my 'class' as following in Javascript:

function MyClass() {

    this.width = 10;
    this.height = 20;

};

But, how do I define my second constructor? I want to be able to create instances of my class two ways:

var Instance1 = new MyClass();
var Instance2 = new MyClass(33,45);

Update:

Ok, I understand my constructors cannot have the same name, because Javascript cannot recognize the different parameter types. So, if I use different names for my constructors, how am I supposed to declare them? Is the following correct?

function MyClass() {

    this.width = 10;
    this.height = 20;

};

MyClass.prototype.New2 = function(w,h) {

    var result = new MyClass();

    result.width = w,
    result.height = h,

    return result;

};

Upvotes: 0

Views: 642

Answers (1)

georg
georg

Reputation: 214959

Javascript has no multimethods, therefore your only option is to parse arguments and act accordingly. A common idiom is to use || to check if an argument is "empty" (undefined or 0):

function MyClass(w, h) {
    this.width = w || 10;
    this.height = h || 20;
};

If 0 is a valid value in your context, check for undefined explicitly:

function MyClass(w, h) {
    this.width  = typeof w != 'undefined' ? w : 10;
    this.height = typeof h != 'undefined' ? h : 20;
};

Another option is to provide arguments as an object and merge it with the "defaults" object. This is a common pattern in jquery:

function MyClass(options) { 
  // set up default options 
  var defaults = { 
    width: 10,
    height: 20
  }; 

  var options = $.extend({}, defaults, options); 

Upvotes: 2

Related Questions