Does the usage of this
in the parameter list of a method in TypeScript fall within the scope?
Take a look at the code snippet below:
class Foo {
constructor(public name) {}
bar(str: string = this.name) { console.log(str); }
}
let f = new Foo("Yo");
f.bar();
The default value of str
is set using this
even when we are not within the body of an instance method.
Currently, in TypeScript 1.8, this approach works as it gets transpiled to:
Foo.prototype.bar = function (str) {
if (str === void 0) { str = this.name; }
console.log(str);
};
Therefore, this
is being utilized within the method, but is this considered compliant?
After a quick look at the specification, I couldn't find a definitive answer.
Please note: This practice is not valid in C++, raising questions about whether it's an intentional feature or simply a byproduct of the transpilation process.