在创建新对象时使用不同类型的参数

时间:2014-08-27 17:28:42

标签: javascript class constructor arguments

我有一个名为Vec的课程。 (向量)

function Vec (x_or_vec,y) {
    this.x;
    this.y;
    switch (arguments.length) {
        case 0:
            this.x = 0;
            this.y = 0;
            break;
        case 1:
            this.x = x_or_vec.x;
            this.y = x_or_vec.y;
            break;
        default:
            this.x = x_or_vec;
            this.y = y;
    }
}

有时我想创建一个新对象而不指定任何有关它的信息,那么,我希望x和y为零。其他时候我想输入要复制的新矢量的矢量,有时我想为新矢量指定x和y坐标。我不喜欢我在示例中使用的方法,对于我制作的某些类,不能使用此方法。

function Box (pos,color,size) {
    this.pos = new Vec(pos);
    this.color = color;
    this.size = new Vec(size);

}

在某些情况下,我想指定颜色,但不是尺寸,在其他情况下,尺寸但不是颜色,在某些情况下,两者都有,而有些则没有。

1 个答案:

答案 0 :(得分:0)

你可以把它传递给一个将文字对象传递给类的JQuery。 像这样初始化:

// don't break if called without arguments 
if(arguments == undefined)
    arguments = {};

// setting default value
this.x = arguments.x || 'some default value';

// checking for object
this.x = (typeof arguments.x === 'object') ? arguments.x.property : arguments.x;

你有很多情况,所以这只是一个指针。