zzzzBov
zzzzBov

Reputation: 179046

How can I make a class constructor be callable as a function?

Some of the top level classes can be instantiated as well as called as a function (e.x. new Number() and Number(), new Boolean() and Boolean(), new Array() and Array()).

Usually this is used for type conversion or as a shortcut for instantiation. I would like to be able to do the same thing:

public class Foo
{
  public function Foo():void
  {
    //do something
  }
}

public function Foo():Foo
{
  //do some stuff;
  return new Foo();
}

Is this possible? If so, how?

EDIT to clarify:

What I wanted to do originally was to create a logging class to interact with Flash/JavaScript, and be cross-browser compatible. I wanted to be able to use the log function as an alias of a method in the log class. This got me to wondering whether I could implement a custom casting function just because. I've now realized it's not possible, but was fun to play with anyway.

Upvotes: 2

Views: 288

Answers (2)

zzzzBov
zzzzBov

Reputation: 179046

You can define classes:

package [package name]
{
  public class Foo
  {
    public function Foo():void
    {
      //do stuff
    }
  }
}

And you can define functions:

package [package name]
{
  public function Foo():Bar
  {
    return new Bar();
  }
}

But the classes and functions cannot have naming collisions. Otherwise you'll get a script error.

A custom casting function cannot be defined with the same name as the class, but it can be implemented under a different name:

package [package name]
{
  public function CastFoo(foo:*):Foo
  {
    //do stuff
    return Foo(foo);
  }
}

Upvotes: 1

momo
momo

Reputation: 3935

this is correct:

public class Foo
{
  public function Foo():void
  {
    //do something
  }
}

this is not:

public function Foo():Foo
{
  //do some stuff;
  return new Foo();
}

if you preceed Foo with "new":

new Foo();

you create a new instance of the Foo class.

if you don't:

Foo();

you get nothing - actually, you'll get a compiler error about missing arguments.

if you pass it a single argument:

var foo:Foo = Foo(bar);

you will cast "bar" as an instance of Foo. The object to be cast must share a super class to be cast. generally it's used for converting a more generic object type into a more specific object type - like casting event.target as a Sprite, or a DisplayObject returned by getChild into a MovieClip.

Upvotes: 0

Related Questions