Skip to content

"this" type #4191

@ylazy

Description

@ylazy

(re-posting from this comment)

In classes, a special type called this refers dynamically to the type of the current class

see (TypeScript this types)

Example:

Class A
{
  public function get foo () :this // return A for class A, return B for class B
  {
    trace("foo");
    return this;
  }
  
  public function sayHello (to:String) :this // return A for class A, return B for class B
  {
    trace("hello" + " " + to);
  }
}

Class B extends A
{
  public static function get wow () :B // if "this" can also be used here?
  {
    trace("wow");
    return new B();
  }
  
  public function get bar () :this // return B
  {
    trace("bar");
    return this;
  }
}

then you can call:

B.wow.foo.bar.sayHello("world!");

output:

wow
foo
bar
hello world!

Another example:

class A
{
  public var content:String;

  public function A(content :String):void
  {
    this.content = content;
  }
  
  public function equals(other : this):Boolean
  {
    return this.content === other.content;
  }
}

class B extends A
{
  public function B(content :String):void
  {
    super(content);
  }
}

then you can call:

var a1:A = new A("wow");
var b1:B = new B("foo");
var b2:B = new B("bar");

trace(b1.equals(b2)); // false
trace(a1.equals(b1)); // TypeError: Error #1034: Type Coercion failed: cannot convert B to A

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions