multiple constructor in 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?
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
}
}
Yes, you can, although not as your expecting. As Javascript is weakly typed, no-one cares or checks what type the arguments that you provide are.
Java requires two different constructors because it is strongly typed and the argument types have to match the method signature, however this isn't the case with JavaScript.
function Point(arg1, arg2) {
if (typeof arg1 === "number" && typeof arg2 === "number") {
// blah
} else if (typeof arg1 === "string" && arguments.length == 1) {
// blah
} else {
throw new Error("Invalid arguments");
}
};
This is inspired from iOS.
class Point {
constructor() {
this.x = 0; // default value
this.y = 0; // default value
}
static initWithCoor(coor) {
let point = new Point();
point.x = coor.x;
point.y = coor.y;
return point;
}
static initWithXY(x,y) {
let point = new Point();
point.x = x;
point.y = y;
return point;
}
}
Just like that, you could have as many initializers as you want without writing lots of if-else.
let p1 = Point.initWithCoor({ x:10, y:20 });
let p2 = Point.initWithXY(10, 20);
链接地址: http://www.djcxy.com/p/51984.html
上一篇: 在开关盒中安装开关盒是不好的做法吗?
下一篇: 在JavaScript中的多个构造函数