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:
class ThisClass { | |
private int someValue; | |
public void setSomeValue(int someValue) { | |
this.someValue = someValue; | |
} | |
public int getSomeValue() { | |
return this.someValue; // works without 'this' | |
} | |
public static void main(String[] args) { | |
ThisClass thisClass = new ThisClass(); | |
System.out.println(thisClass.getSomeValue()); // 0 | |
thisClass.setSomeValue(42); | |
System.out.println(thisClass.getSomeValue()); // 42 | |
} | |
} |
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).
function test() { | |
console.log(this); | |
} | |
const test2 = () => console.log(this); | |
const bigObject = { | |
someValue: 42, | |
test, | |
test2 | |
} | |
bigObject.test(); | |
/* | |
{ someValue: 42, | |
test: [Function: test], | |
test2: [Function: test2] } | |
*/ | |
bigObject.test2(); | |
/* | |
{} | |
*/ |
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:
const foo = { someValue: 1 }; | |
const test = bigObject.test.bind(foo); | |
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.