2

I am reading this answer: https://stackoverflow.com/a/632914/840992 and I don't understand why one would define the function as a var:

var setPrecision:Function = function(number:Number, precision:int) {
 precision = Math.pow(10, precision);
 return Math.round(number * precision)/precision;
}

var number:Number = 10.98813311;
trace(setPrecision(number,1)); //Result is 10.9
trace(setPrecision(number,2)); //Result is 10.98
trace(setPrecision(number,3)); //Result is 10.988 and so on

Rather than just a function:

public function setPrecision(number:Number, precision:int) {
    precision = Math.pow(10, precision);
    return Math.round(number * precision)/precision;
}

I am using classes for everything. I can understand it if one wanted to pass the var around, etc. but as just a utility to set float precision, I am not seeing the value here. All of the related questions I have seen pertain to JavaScript.

Am I correct in thinking that in a class, there is no good reason for defining this function as a var?

Community
  • 1
  • 1
spring
  • 18,009
  • 15
  • 80
  • 160
  • Maybe a throwback to early [ActionScript OOP](http://help.adobe.com/en_US/ActionScript/3.0_ProgrammingAS3/WS5b3ccc516d4fbf351e63e3d118a9b90204-7f3f.html) using prototype; otherwise, function pointer may make sense if there were unique operations for different use cases. I'd promote that to a static method. – Jason Sturges Jan 24 '15 at 23:34

2 Answers2

0

There's no good reason for that, unless you want to pass this function as a parameter. It's just another way to write the same thing.

gilamran
  • 7,090
  • 4
  • 31
  • 50
0

In case the var is a member of the class and not a local function within a method the difference would be that you could overwrite the function in each object to change some behaviour.

public class Foo {
    /**
    * By default we'll square the value to prepare it
    */
    public var prepareSomething:Function = function(n:Number):Number {
        return n * n;
    }

    public function doSomething(n:Number) {
        var x = this.prepareSomething(n);
        // do something with x
    }
}

Now you could have something like this:

var foo = new Foo();
// we prefer to have n cubed for preparation here...
f.prepareSomething = function(n:Number):Number {
    return n * n * n;
}
foo.doSomething(123.45);

Usually that'll not be a very good design idea, but at some point it might come handy.

I don't know if a local function would be handled somehow different when defined as a var. There might be a difference in allocation or deallocation.

Otherwise one might find the var style just a little clearer: yes this function really is meant to be local. Functionally there's no difference, both ways can be passed as an argument etc.

David Triebe
  • 375
  • 1
  • 5