Skip to main content
Inspiring
March 10, 2008
Question

global function

  • March 10, 2008
  • 2 replies
  • 317 views
Hi,

is it possible to create a global function like in AS2? I tried a bit to
create a class that does it but wasn't succesfully. Well I am new to
class programming...


class rand {
public var random
public function random (to:int):int{
return Math.ceil(Math.random() * to);
}
}
This topic has been closed for replies.

2 replies

Inspiring
March 11, 2008
Ok thanks,

is it possible to add a function to the Math class? So I would be able
to use a command like "Math.randomTo(123);"
Craig Grummitt
Inspiring
March 11, 2008
it is possible to add functions to classes that are defined as dynamic. Array for example, is dynamic, and you could add a function to its prototype like so:
Array.prototype.shuffleArray=function() {
//shuffle array here
}

Math, unfortunately is defined as final, and functions can not be added to it. you would need to define a subclass of Math.

if you want more reading on this, click here.
Craig Grummitt
Inspiring
March 11, 2008
with that type of utility function you'd be best off declaring the function as static eg.
public static function random(to:int):int {

and then you would be able to call it like so:
trace(rand.random(x));

otherwise, you would need to instantiate the class before you would be able to call any functions eg:
trace(new rand().random(x));

or
var randy:rand=new rand();
trace(randy.random(x));