I am reading a code like below:
export abstract class CustomError extends Error {
abstract statusCode: number;
constructor(message: string) {
super(message);
Object.setPrototypeOf(this, CustomError.prototype);
}
abstract serializeErrors(): { message: string; field?: string }[];
}
I can't understand what does this
refer to? I think in this case this
should be equal to CustomError
, and if so, this expression would be meaning less to me:
Object.setPrototypeOf(this, CustomError.prototype);
Because it's like:
Object.setPrototypeOf(this, this.prototype);
And it assigns the class's prototype to an object of same class's prototype that I can't understand the reason? I mean this
should have this prototype itself by default, shouldn't it?
CodePudding user response:
this reffers to the variable itself. If I made a class,
class thing{
constructor() {console.log(this)}
}
new thing();
"this" reffers to the class.
CodePudding user response:
Just like it says in the code
Object.setPrototypeOf(this, CustomError.prototype);
this represents or refers to an object in javascript