Monday, June 3, 2024
72
rated 0 times [  79] [ 7]  / answers: 1 / hits: 105312  / 7 Years ago, wed, april 26, 2017, 12:00:00

Why am I getting the error: Uncaught TypeError: self.myTest is not a function? How do I call a method from within another method in a javascript class?





class MyClass {

myTest() {
console.log('it works');
}

runMyTest() {
self.myTest();
}

}

var myClass = new MyClass();
myClass.runMyTest();




More From » ecmascript-6

 Answers
6

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();




[#57992] Tuesday, April 25, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
micayla

Total Points: 148
Total Questions: 92
Total Answers: 109

Location: Aruba
Member since Sat, Oct 2, 2021
3 Years ago
micayla questions
Fri, Dec 24, 21, 00:00, 2 Years ago
Thu, Apr 16, 20, 00:00, 4 Years ago
Thu, Nov 14, 19, 00:00, 5 Years ago
;