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;
};