Can someone explain to me the use of the word "this"? I used it in JavaScript to refer to a particular object, but I am not too clear of its use in Java.
Printable View
Can someone explain to me the use of the word "this"? I used it in JavaScript to refer to a particular object, but I am not too clear of its use in Java.
Have look at this tutorial it should make it clear for you
'this' refers to the instance on which the method is currently being called. For example, if you have:It serves roughly the same function in Java as in Javascript, but has vastly different mechanics due to the differences between the two languages.Code:class Foo {
public string baz;
public String bar() {
return this.baz;
}
public static void main(String[] args) {
Foo f = new Foo();
Foo.baz = "fish";
System.out.println((new Foo()).bar()); // Will print 'fish'.
}
}
I understand the purpose it it, but I am still not very clear. I guess I'll have to keep on reading until the clouds disipate and the light breaks through. Thanks.
This article I wrote might help you, Javascript-oriented though it be: http://fn-js.info/faqs/context. The same principle applies to Java, although methods are not truly properties in Java, since it doesn't have first-class functions.
I finally got it. Thanks Twey and everyone for your help. I guess I need to relax and not streess over it so much and eventually the clouds will disipate and sunlight will shine through (figuratively speaking). Thanks again.