大家好,大家好.我只想创建一个简单的Dice对象,它允许用户为骰子实例化时的“侧”数选择一个“自定义”或“默认值”。同时,“侧”不是对象的静态属性。而且,唯一可用的接口是Dice.roll。你认为这是一个公平的解决方案吗?
function Dice(num){
var sides = (num) ? num : 6;
this.roll = Math.floor(Math.random() * sides + 1); // The interface
}
var defaultdice = new Dice(); // Default Dice, 6 sides
var dice4 = new Dice(4); // 4 sides Dice
var dice2 = new Dice(2); // 2 sides Dice
console.log(defaultdice.roll,' ',dice4.roll,' ',dice2.roll);发布于 2018-09-02 16:05:49
你认为这是一个公平的解决方案吗?
对我来说很公平!你凭什么认为这“不公平”?
如果需要多次滚动相同的Dice实例,我建议将roll属性转换为函数;如下所示,
function Dice(num) {
var sides = (num) ? num : 6;
this.roll = function() {
return Math.floor(Math.random() * sides + 1);
}
}
var defaultdice = new Dice(); // Default Dice, 6 sides
var dice4 = new Dice(4); // 4 sides Dice
var dice2 = new Dice(2); // 2 sides Dice
console.log(defaultdice.roll(), ' ', dice4.roll(), ' ', dice2.roll());
// Sides is a private class member
// Trying to access it from the instance will return undefined
console.log(dice4.sides);
https://stackoverflow.com/questions/52138661
复制相似问题