This project is read-only.

Confusing interface example

Topics: General
Oct 3, 2012 at 9:22 AM

Example 5 from the tutorial has me confused. The `Person' interface declares `firstname' and `lastname' members while the `Student' class declares only one member: `fullname' yet we are able to provide a `Student' object where a `Person' is expected?? Looking at the generated JavaScript we see that `firstname' and `lastname' members are automagically created for us from the ctor parameters of the same name. This behaviour seems somewhat unintuitive to me & I'd love to know what the reasoning behind it was.

Oct 3, 2012 at 9:59 AM

I believe it is that the constructor parameters if declared as public should be attached to the instance. It is kind of a shorthand for

function Student(firstname, lastname) {
  this.firstname = firstname;
  this.lastname = lastname;

Seems reasonable.

Oct 3, 2012 at 1:10 PM

That's right - the 'public' modifier on a constructor parameter is a shorthand for declaring each of (a) a constructor parameter, (b) a property of the corresponding type, and (c) an initialization of the property to the constructor parameter.  This combination was common enough that we added a shorthand syntax.