Calling a method from another method in the same class
class MyClass {
myTest() {
console.log('it works');
}
runMyTest = ()=>{
this.myTest();
}
runMyTest2 = function(){
this.myTest();
}
}
var myClass = new MyClass();
myClass.runMyTest(); myClass.runMyTest2();
use arrow function to bind this to the global object. To represnt objects properties we have to use function
let user = {
name :"Something
}
user.value = ()=>{
console.log(this)
}
user.value2 = function(){
console.log(this)
}
user.value(); ///returns this for windows
user.value2(); ///returns object user
class MyClass {
myTest() {
console.log('it works');
}
runMyTest() {
this.myTest();
}
}
var myClass = new MyClass();
myClass.runMyTest();
You need to use the this
keyword instead of self
.
runMyTest() {
this.myTest();
}
A side note
If you are nesting standard functions notation then this
is not lexically bound (will be undefined). To get around this, use Arrow Functions (preferred), .bind
, or locally define this
outside of the function.
class Test {
constructor() {
this.number = 3;
}
test() {
function getFirstThis() {
return this;
}
const getSecondThis = () => {
return this;
};
const getThirdThis = getFirstThis.bind(this);
const $this = this;
function getFourthThis() {
return $this;
}
// undefined
console.log(getFirstThis());
// All return "this" context, containing the number property
console.log(this);
console.log(getSecondThis());
console.log(getThirdThis());
console.log(getFourthThis());
}
}
new Test().test();
You need to use this
not self
like
runMyTest() {
this.myTest();
}
However a lot of implementations like to keep the reference and are doing the following:
var self = this;
That might be the reason you were thinking of self
as self reference. For further reading I'd suggest this SO - post