js从静态方法创建对象

时间:2015-04-11 10:13:05

标签: javascript oop

下午好!我有一些对象作为“坐标”,我可以使用两个参数(x,y)从构造函数中调用它。但我想用另一种方式,从没有参数的静态方法调用构造函数(生成随机)

/**
 * @param {int} x
 * @param {int} y
 * @constructor
 */
var Coordinates = function (x, y) {

    if (!(x >= 0 && y >= 0)) {
        throw new Error('Coordinates is not correctly!');
    }

    this.x = x;
    this.y = y;

    Coordinates.generateRandom = function () {
        var randomX = Math.round(Math.random() * 500);
        var randomY = Math.round(Math.random() * 500);
        return new Coordinates(randomX, randomY);
    };

    this.toString = function () {
        return this.x + ', ' + this.y;
    };
};

//var position = new Coordinates(114, 12); // first way

var position = Coordinates.generateRandom(); // or second way

1 个答案:

答案 0 :(得分:0)

所以你只想让Coordinates拥有静态方法generateRandom()?然后只需将该方法移出您的类定义(请参阅jsfiddle):

/**
 * @param {int} x
 * @param {int} y
 * @constructor
 */
var Coordinates = function (x, y) {
    if (!(x >= 0 && y >= 0)) {
        throw new Error('Coordinates is not correctly!');
    }

    this.x = x;
    this.y = y;

    this.toString = function () {
        return this.x + ', ' + this.y;
    };
};

Coordinates.generateRandom = function () {
    var randomX = Math.round(Math.random() * 500);
    var randomY = Math.round(Math.random() * 500);
    return new Coordinates(randomX, randomY);
};

var position = Coordinates.generateRandom(); // or second way
console.log(position);

以上代码的Chrome控制台输出示例:

Coordinates
    toString: function () { ...
    x: 226 y: 132
    __proto__: Coordinates ...