JavaScript - 函数之间的随机数和变量

标签 javascript function variables

我是 JavaScript 新手,对于框架的每个滚动,我都有两个滚动函数。我无法将每个卷的值放入框架函数中以供调用和使用。如果有人可以提供帮助,那就太好了!预先感谢,我的代码如下。

var Bowling = function() {
  var STARTING_TOTAL = 0;
  ROLL_ONE = Math.floor(Math.random() * 11);
  ROLL_TWO = Math.floor(Math.random() * 11);
  this.score = STARTING_TOTAL;
  var firstScore;
  var secondScore;
  var totalScore;

  Bowling.prototype.firstRoll = function() {
     firstScore = ROLL_ONE
     return firstScore;
  };

  Bowling.prototype.secondRoll = function() {
     secondScore =  Math.floor(Math.random() * 11 - firstScore);
     return secondScore;

  };

  Bowling.prototype.frameScore = function () {
     totalScore = firstScore + secondScore
    return totalScore;
  };

};

最佳答案

我只能猜测你想要实现什么目标。我稍微重构了你的代码:

var Bowling = function () {
  var STARTING_TOTAL = 0;
  this.score = STARTING_TOTAL; // remains unused; did you mean "totalScore"?
  this.firstScore = 0;
  this.secondScore = 0;
};

Bowling.prototype.firstRoll = function () {
  this.firstScore = Math.floor(Math.random() * 11);
  return this.firstScore;
};

Bowling.prototype.secondRoll = function () {
  this.secondScore = Math.floor(Math.random() * 11 - this.firstScore);
  return this.secondScore;

};

Bowling.prototype.frameScore = function () {
  this.totalScore = this.firstScore + this.secondScore
  return this.totalScore;
};

// now use it like this:
var bowling = new Bowling();
console.log(bowling.firstRoll());
console.log(bowling.secondRoll());
console.log(bowling.frameScore());

但是,在我的方法中,firstScoresecondScore 是公共(public)属性。

关于JavaScript - 函数之间的随机数和变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44606848/

相关文章:

javascript - 调用函数时如何传入参数名称?

function - golang中固定cos数学函数有没有解决办法

asp.net - 用于在按键时跳到文本框的 Jquery 函数

c++ - 将文件内容存储到C++中的变量中

javascript - 如何使用javascript捕获旧值并将其设置回取消

JavaScript - 将两个 JSON 请求组合成一个对象

javascript - JQuery 检查变量是否是函数

function - Azure 函数中的报告查看器 DLL 加载问题

variables - 如何通过文字进行模式匹配并同时为其分配变量?

variables - 变量名和逗号后面的下划线的作用是什么?