创建一个简单的Dice对象,界面中没有静态的“sides”属性

问题描述 投票:1回答:1

你好社区中的所有人...我只是想创建一个简单的Dice对象,允许用户为骰子在实例化时具有的“边”数选择“自定义”或“默认”值。同时,'sides'不是对象的静态属性。而且,唯一可用的界面是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);
javascript function constructor
1个回答
0
投票

你认为这是一个公平的解决方案吗?

看起来对我很公平!是什么让你相信这是“不公平的”?


如果您需要多次滚动相同的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);
© www.soinside.com 2019 - 2024. All rights reserved.