首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >创建一个简单的Dice对象,而接口中没有静态的“侧”属性

创建一个简单的Dice对象,而接口中没有静态的“侧”属性
EN

Stack Overflow用户
提问于 2018-09-02 15:57:47
回答 1查看 56关注 0票数 1

大家好,大家好.我只想创建一个简单的Dice对象,它允许用户为骰子实例化时的“侧”数选择一个“自定义”或“默认值”。同时,“侧”不是对象的静态属性。而且,唯一可用的接口是Dice.roll。你认为这是一个公平的解决方案吗?

代码语言:javascript
复制
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);
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-09-02 16:05:49

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

对我来说很公平!你凭什么认为这“不公平”?

如果需要多次滚动相同的Dice实例,我建议将roll属性转换为函数;如下所示,

代码语言:javascript
复制
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);

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52138661

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档