2

x および y インスタンス変数を生成する randomInt メソッドを使用して、coffeescript でクラスを作成しました。ただし、このクラスからオブジェクトを作成すると、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 にはこのネイティブ関数がありません。

4

1 に答える 1

3

xandの「インスタンス変数」を作成しますy(@そのような変数になります):

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)

于 2012-07-23T19:19:55.130 に答える