this
is not a variable. It functions more like a concealed argument in functions.
In the given example, you cannot access self
because it is a local variable confined within the constructor and therefore unavailable to your assemble
method.
For this particular scenario, you actually do not require self
at all; simply utilize this
:
class Form {
assemble(){
log(this); // ***
}
}
var form = new Form();
form.assemble();
If you were passing form.assemble
into something where the correct usage of this
was not guaranteed, you could define assemble
as an instance function member by defining it within the constructor; thus closing over self
. Nonetheless, in ES2015 and beyond, there is no need for self
; instead, use an arrow function which closes over this
:
class Form {
constructor(){
var self = this;
this.assemble = () => {
log(this);
};
}
}
var form = new Form();
form.assemble(); // Functions correctly
var f = form.assemble;
f(); // Also works fine
However, chances are high that this additional step is unnecessary.