js 从静态方法创建对象



下午好!我有一些对象作为"坐标",我可以用两个参数(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

所以你只想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 ...

最新更新