JavaScript code below.
class Test{
testMethod1() {
console.log('hello world');
}
testMethod2() {
this.testMethod1();
}
}
let t = new Test();
t.testMethod1();
t.testMethod2();
I already know that when calling a method from another method in the same class needs a this pointer.
But why JavaScript need this?
Seems that cpp, java and othter object oriented langauge do not need this.
this in this context means you refer to the current object which is just instantiated by new. Without this, the compiler will understand that you refer to an outer-scoped function.
function testMethod1() {
console.log('outer world');
}
class Test{
testMethod1() {
console.log('hello world');
}
testMethod2() {
testMethod1(); //removed `this`
}
}
let t = new Test();
t.testMethod1(); //hellow world
t.testMethod2(); //outer world
I'm not sure where you are pointing out that Java or other object-oriented programming languages do not need this. You can try this playground for Java.