JS CoffeeScript-来自方法的相同随机数
JS CoffeeScript - Same random number from method
我用一个生成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没有这个原生函数。
创建x
和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)
打印的:
4813986
注意,getRandomInt
函数被添加到Shape.prototype
,并且Shape::getRandomInt(1,100)
与Shape.prototype.getRandomInt(1,100)
相同。
相关文章:
- electronic BrowserWindow的最小高度和宽度在hide()show()方法之后不起作用
- 有没有任何方法可以将控制器从文件加载到ui路由器$stateProvider中
- 数组在递归方法中设置为null
- 打破承诺链的好方法是什么
- 在使用Polymer'加载所有json文件后执行方法;s的核心ajax
- 使用“;这个“;JavaScript原型方法中的关键字
- 序列化数据属性中对象的最可靠方法
- 使用Objective-C的JavaScript注入方法
- 有没有一种方法可以添加相同的项目val=“0”;4〃;到JavaScript中数组的每个对象
- 有没有一种方法可以防止img get请求使用css或js发生
- Javascript,有没有一种方法可以将数组写成没有逗号或空格的单个文本字符串
- toBoolean方法类似于toString
- 如何在单击复选框后调用控制器方法
- 是否有任何方法可以使用jQuery替换在数组中定义值的文本
- 递归使用 eval() 是检查程序执行的好方法吗?
- 如何在webView,Android中从@JavascriptInterface方法调用Javascript
- 在 JavaScript 中获取范围的随机数的最佳方法
- 随机数生成器,what'我的方法/统计数据有问题吗?[JS]
- JS CoffeeScript-来自方法的相同随机数
- 在 JavaScript 中获取随机数的最佳方法是什么?