Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

multiple constructor in javascript

Tags:

javascript

I have a question: I was wondering if it is possible to simulate the multiple constructors, like in Java (yes, I know that the languages are completely different)?

Let's say that I have a class called "Point" which would have two values "x" and "y".

Now, let's say if it were the Java version, I would want two constructors: one that accept two numbers, the other accepts a string:

public class Point {
    private int x;
    private int y;
    public Point(int x, int y) {
        this.x = x;
        this.y = y;
    }
    public Point(String coord) {
        this.x = coord.charAt(0);
        this.y = coord.charAt(1);
    }
    //...
}


//In JavaScript, so far I have
Point = function() {
    var x;
    var y;
    //...
}

Is it possible to have two declarations for the Point.prototype.init? Is it even possible to have multiple constructors in JavaScript?

like image 618
Arslan Ahson Avatar asked Sep 20 '11 08:09

Arslan Ahson


1 Answers

You can do this in javascript by testing the number of arguments, or the type of the arguments.

In this case, you can do it by testing the number of arguments:

function Point(/* x,y | coord */) {
    if (arguments.length == 2) {
        var x = arguments[0];
        var y = arguments[1];
        // do something with x and y
    } else {
        var coord = arguments[0];
        // do something with coord
    }
}
like image 95
Arnaud Le Blanc Avatar answered Dec 21 '22 20:12

Arnaud Le Blanc