es-explicit-this
es-explicit-this copied to clipboard
explicit `this` and class constructor
TypeScript do not allow this
parameter in constructor.
class Test {
constructor(this: any) { // <-- Error: A constructor cannot have a 'this' parameter.ts(2681)
//...
}
}
It's very clear in derived class case:
class A extends B {
constructor(this) { // <-- What `this` mean here??
this // <-- throw ReferenceError
super() // <-- `this` is only available after `super()`
}
}
In base class case, even we can access this
in the very beginning
class A {
constructor() {
console.log(this) // ok
}
}
class B {
constructor(x = this) { // <-- also ok, though TS report error:
// 'this' cannot be referenced in constructor arguments.ts(2333)
}
}
IMO we should also not allow explicit this
in base class, because this
in the constructor is never a parameter or argument passed by caller, but generated by the constructor itself.
Actually I feel we should make explicit this
and constructor mutually exclusive, which means for
function f(this) {}
we should not allow new f()
(throw TypeError) because in the new f()
form, this
is not an argument/parameter.
Essentially we should make f
have no [[Construct]]
internal method and no prototype
property just like arrow functions, methods and accessors and all built-in non-constructor functions.
So explicit this
will also provide a way to allow programmers clearly mark a function as a "method" without forcing them use method syntax.