0

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.

Machi
  • 403
  • 2
  • 14
  • 1
    *But why JavaScript need this?* because that's how it works - it's like asking "why do you need to use `new`" or "why does if need the condition in ()" - it's how the language works - I've never understood the rationale of questioning the syntax of a programming language – Bravo Jun 18 '22 at 04:22

1 Answers1

3

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.

Nick Vu
  • 14,512
  • 4
  • 21
  • 31
  • 2
    "*Javascript is not designed for object-oriented originally*" - huh? JavaScript very much is an object-oriented language at its core, and a much better object-oriented language than e.g. the class-oriented Java. – Bergi Jun 18 '22 at 05:21
  • I think the link to the Java playground is broken – Bergi Jun 18 '22 at 05:22
  • Thank you for your feedback! Javascript is a functional programming language originally, you can check [this reference](https://opensource.com/article/17/6/functional-javascript) @Bergi – Nick Vu Jun 18 '22 at 05:39
  • 3
    @NickVu Your explanation of `this` and especially the 1st example deserves an upvote. But please remove your claim... _"Javascript is not designed for object-oriented programming originally but for functional programming"_ ...since it is utterly wrong. And backing it up with a link to it's history and influences of Lisp/Scheme is not a proof for any un/fulfilled PL paradigm. As Bergi says, the core language is as OO as can be since JS from the beginning did support Encapsulation (closures), Polymorphism (ad hoc, parametric, dynamic dispatch) and Inheritance (prototype chain). **OO !== class** – Peter Seliger Jun 18 '22 at 08:04
  • 2
    @NickVu From that very reference: "*JavaScript is a multi-paradigm language that allows you to freely mix and match object-oriented, procedural, and functional paradigms.*" – Bergi Jun 18 '22 at 11:22
  • 1
    Thank you both for your support! Today I have learned it! :D – Nick Vu Jun 18 '22 at 16:12