I've noticed a discrepancy in @basarat's response. Please consider adding the following:
let bar = new SomeClass();
console.log(bar.fooBar());
The outcome is 1
because fooBar
isn't a method but a field that happens to be a function. Hence, each SomeClass
instance has its own closure for fooBar
with its unique foo
.
In my opinion, for a true simulation of a static local variable similar to C++, the correct answer should be 3. This is because the one method and one foo
are shared among all instances. To achieve this in Typescript, you can define fooBar
after the class declaration:
SomeClass.prototype.fooBar = (function() {
let foo = 1;
function fooBar() {
return foo++;
}
return fooBar;
})();
Furthermore, I've utilized a different approach to create the closure, avoiding the need for a new class and steering clear of arrow notation. This ensures clarity regarding the reference of this
if fooBar
ever requires access to instance members.
If required, you could also insert a placeholder definition of fooBar()
within the class body for type checking purposes; the subsequent external definition will overwrite it seamlessly.