Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>This works as well, and is perhaps closer to the original:</p> <pre><code>class Class1 { id:number; constructor(s: string) { (n:number) =&gt; { this.id = n; }(s.length) } } var t:Class1 = new Class1("HELLO"); console.log("Class1ID: " + t.id); // Output = Class1 ID: 5 </code></pre> <p>For reference, here's the output JS:</p> <pre><code>var Class1 = (function () { function Class1(s) { var _this = this; (function (n) { _this.id = n; })(s.length); } return Class1; })(); var t = new Class1("HELLO"); console.log("Class1 ID: " + t.id); </code></pre> <p><strong>Update</strong></p> <p>If you have to be able to call the constructor with just an ID, then I think you'll have to use a factory method, as Steve has suggested. And, since I don't think TS constructors can be private, if you need that method to be private you'll have to dispense with the constructor altogether and use a pair of factory methods. The first instance might look something like this:</p> <pre><code>class Class1 { constructor(public id:number) {} // Public, unfortunately. static Fabricate(s:string):Class1 { return new Class1(s.length); } } var classA:Class1 = new Class1(1); var classB:Class1 = Class1.Fabricate("Hello"); console.log(classA.id); // "1" console.log(classB.id); // "5" </code></pre> <p>And the second something like this:</p> <pre><code>class Class1 { id:number; private static fabricate(n:number):Class1 { var class1:Class1 = new Class1(); class1.id = n; return class1; } static Fabricate(s:string):Class1 { return fabricate(s.length); } } var classA:Class1 = Class1.Fabricate("Hello"); console.log(classA.id); // "5" </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload