JS CoffeeScript-来自方法的相同随机数

JS CoffeeScript - Same random number from method

本文关键字:随机数 方法 CoffeeScript- JS      更新时间:2024-01-26

我用一个生成x和y实例变量的randomInt方法在coffescript中创建了一个类。然而,当我从这个类创建对象时,x和y的值是不同的,但两者都是一致的。

以下是要演示的代码:http://jsfiddle.net/paulmason411/BvPBG/

class Shape
  getRandomInt = (min, max) ->
    Math.floor(Math.random() * (max - min + 1)) + min
  y: getRandomInt(1,100)
  x: getRandomInt(1,100)
shape1 = new Shape
shape2 = new Shape
alert(shape1.x)
alert(shape2.x)
alert(shape1.y)
alert(shape2.y)​

我需要每个警报值都不同。

我搜索了一个解决方案,在其他编程语言中他们使用srand(),但是js没有这个原生函数。

创建xy的"实例变量"(@使它们成为这样的变量):

class Shape
  constructor: ->
    @x = Shape::getRandomInt(1,100)
    @y = Shape::getRandomInt(1,100)
  getRandomInt: (min, max) ->
    Math.floor(Math.random() * (max - min + 1)) + min

shape1 = new Shape
shape2 = new Shape
console.log(shape1.x)
console.log(shape2.x)
console.log(shape1.y)
console.log(shape2.y)

打印的:

4813986

注意,getRandomInt函数被添加到Shape.prototype,并且Shape::getRandomInt(1,100)Shape.prototype.getRandomInt(1,100)相同。