Self type

Brendan Eich brendan at
Mon Aug 13 14:40:12 PDT 2007

On Aug 13, 2007, at 1:59 PM, Peter Hall wrote:

>>> Or can't Self be used outside of the sorts of usage found in the
>>> proposal examples?
>> That's it.
> In that case, I think it needs to be clearer about how the syntax can
> be used.

No doubt the proposal needs to be clearer to become a spec.

> Is it only for use as the "this" parameter for function
> types?

No, but it is only for function types within object structural types.  
See the "Use Cases" section:

     * clone, iterators: {f:function():Self}
     * binary methods, equals: { f : function(x:Self):boolean }
     * structural object methods: { f : function(this:Self, ...) } -  
only useful if structural objects with types


Note that the "same type" case, equals, requires a runtime check to  
be generated. This eliminates the kind of instanceof or downcasting  
hand-written boilerplate seen in Java's equals implementations.

> Seems to me like it should be usable anywhere that the compiler
> can reasonably detect the type at compile-time.
> e.g.
> // this usage is handy for boiler-plate code that you can just copy
> // and paste without modification, or from an IDE code snippet  
> template
> class A {
> var a:Self;
> // or...
> // var a:this type;
> }

This is not a strong motivation IMHO.

> type B = {b:Self};

We don't allow recursive structural types in general, but this kind  
of degenerate cycle might be ok. Cormac should comment.

> Other places where special treatment of the keyword would be useful is
> in interfaces, where the a function argument or return value should be
> the same as the type:
> interface IClonable {
> public function clone():Self;
> }
> class A implements IClonable {
>   public function clone():A { return new A() };
> }

Indeed -- those are use-cases for interfaces and classes as well as  
for structural types. However, the proposal is focused on structural  
types since unlike classes, |this| binding defaults to the dynamic  
rule from ES1-3, which is weak.

> That is, users of the interface see the type as being the same as the
> interface, but implementors must use their own type here. The example
> is identical to clone's return type being IClonable, except that
> implementors are required to declare a stronger type.

Good point. I'll defer to Cormac on commenting further.


More information about the Es4-discuss mailing list