gpt4 book ai didi

javascript - js通过静态方法创建对象

转载 作者:行者123 更新时间:2023-11-28 07:26:40 25 4
gpt4 key购买 nike

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

最佳答案

所以你只是想让Cooperatives有静态方法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 ...

关于javascript - js通过静态方法创建对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29576663/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com