This Alias
ID |
javascript.this_alias |
Severity |
high |
Remediation Complexity |
medium |
Remediation Risk |
low |
Remediation Effort |
medium |
Resource |
Code Smell |
Language |
JavaScript |
Tags |
code-style, legacy, readability |
Description
Reports a variable declared to hold this — the const self = this that predates arrow functions.
Destructuring this (const {width, height} = this;) is not reported: it takes values out of the receiver rather than giving the receiver a second name, and there is no arrow-function rewrite to move to.
Every alias name is reported, not a fixed list of self / that / _this. The name is not what makes the pattern worth changing.
Rationale
// Bad
Uploader.prototype.start = function (files) {
const self = this;
files.forEach(function (file) {
self.send(file);
});
};
-
The alias exists only to carry the receiver into a nested
function, which rebindsthisto its own call site. -
The reader now has two names for the same object and has to track which one is in scope where.
-
The alias survives refactorings that move the inner function elsewhere — at which point it silently captures a
thisfrom a different call. -
A search for
this.sendno longer finds the call site.
Remediation
Use an arrow function. It does not rebind this, so the alias has nothing left to do.
// Good
Uploader.prototype.start = function (files) {
files.forEach(file => this.send(file));
};
// Good — destructuring takes values out, it does not rename the receiver
render() {
const { width, height } = this;
return width * height;
}