【问题标题】:JS CoffeeScript - Same random number from methodJS CoffeeScript - 方法中的相同随机数
【发布时间】:2012-07-23 19:07:08
【问题描述】:

我在 coffeescript 中创建了一个类,该类使用 randomInt 方法生成 x 和 y 实例变量。但是,当我从此类创建对象时,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 没有这个原生函数。

【问题讨论】:

    标签: javascript object random coffeescript


    【解决方案1】:

    创建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)
    

    打印出来的:

    48
    13
    9
    86

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

    【讨论】:

      猜你喜欢
      • 2019-02-20
      • 1970-01-01
      • 2021-02-21
      • 2022-11-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-14
      • 1970-01-01
      相关资源
      最近更新 更多