Menu Close

From Java to JavaScript – This

Java and JavaScript have some things in common, but also do most of them differently. One example for that is this. This refers mostly to a specific context, meaning that some variables are only available in this context.

Java – this

In Java, this is used to access member variables. So it is used to access the context of the class:

  1. class ThisClass {
  2.   private int someValue;
  3.  
  4.   public void setSomeValue(int someValue) {
  5.     this.someValue = someValue;
  6.   }
  7.  
  8.   public int getSomeValue() {
  9.     return this.someValue; // works without 'this'
  10.   }
  11.  
  12.   public static void main(String[] args) {
  13.     ThisClass thisClass = new ThisClass();
  14.  
  15.     System.out.println(thisClass.getSomeValue()); // 0
  16.  
  17.     thisClass.setSomeValue(42);
  18.  
  19.     System.out.println(thisClass.getSomeValue()); // 42
  20.   }
  21. }

So in Java, especially in setter functions, the parameter often has the name as the variable that it is intended to set. In this example, someValue is ambiguous, that’s why this makes sense. The getter works without this, because there is no ambiguity in that context.

JavaScript – this

In JavasScript, this refers to the ‘call context’. If you use it inside a function, you will access its object (bigObject in this example).

  1. function test() {
  2.   console.log(this);
  3. }
  4.  
  5. const test2 = () => console.log(this);
  6.  
  7. const bigObject = {
  8.   someValue: 42,
  9.   test,
  10.   test2
  11. }
  12.  
  13. bigObject.test();
  14. /*
  15. { someValue: 42,
  16.   test: [Function: test],
  17.   test2: [Function: test2] }
  18. */
  19.  
  20. bigObject.test2();
  21. /*
  22. {}
  23. */

There are many other places in JavaScript, where this has its use. For example in HTML event handlers, this refers to the received event. Binding in JavaScript is a whole topic for itself, but in short you can have a look at the last example:

  1. const foo = { someValue: 1 };
  2. const test = bigObject.test.bind(foo);
  3.  
  4. test(); // { someValue: 1 }

In this example, we change the this context of the test() method inside bigObject to foo. This an important concept in JavaScript, especially when you want to invoke a method at a later time, but in a different context. That could be a button click or timer, which want to access or even change data from a different context.

Leave a Reply

Your email address will not be published. Required fields are marked *

1 × 3 =

This site uses Akismet to reduce spam. Learn how your comment data is processed.