PDA

View Full Version : "this"



xtiano77
09-26-2008, 04:50 AM
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.

peter_budo
09-26-2008, 08:24 AM
Have look at this tutorial (https://java.sun.com/docs/books/tutorial/java/javaOO/thiskey.html) it should make it clear for you

Twey
09-26-2008, 04:54 PM
'this' refers to the instance on which the method is currently being called. For example, if you have:
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'.
}
}It serves roughly the same function in Java as in Javascript, but has vastly different mechanics due to the differences between the two languages.

xtiano77
09-26-2008, 09:17 PM
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.

Twey
09-27-2008, 08:18 AM
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.

xtiano77
10-07-2008, 03:38 AM
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.