Loading...
Logo
Processing Forum
I've been trying to understand the use of (this) when referring to the current object.   Does (this) reference the sketch that is being written or does it refer to the last object encountered in the sketch?  What is the current object, I'm new to the use of objects.

Replies(12)

If this is inside a class (that is, a code within a class block),
it refers to that class itself (or an instance of it).
If it's outside any class, it refers to the sketch.
And sketch is a class itself (extends PApplet's)!
Thanks for your answer, it makes sense to me now.  I've looked at several books and the javadoc and it wasn't as clear as your answer.

Thanks
WPK


argh...

I need a reference to the sketch/applet within a class.

When I use " this", it gives me the class, but I need the skecth...
What about this:

Copy code
  1. A a;

  2. void setup() {
  3.   a = new A(this);
  4.   a.doStuff();  
  5. }
  6. void draw() {}

  7. public class A{
  8.   PApplet p;
  9.  
  10.   A(PApplet p) {
  11.     this.p = p;
  12.   }  
  13.   
  14.   void doStuff() {
  15.     p.println("stuff");
  16.   }  
  17. }
Excellent example timpulver!

Pass the this belonging to sketch, and when it's still inside one of the sketch's methods, as a PApplet parameter to the class which needs to know about it!

this approach is quite longwinded, since my class is called from another class so I have to pass "this" on twice......

I thought it might exist a global var like displayHeight holding the reference to the sketch no matter whether you are in a class or not.

What is worse, my code doesn't work at all but it doesn't tell why or where....

Thanks!



It might be longwinded, but that's the classical method: look at all the libraries — most of them have this in the constructor.
Note that nothing prevents you to make a global variable yourself, that you assign with the  this value.
Like this one?:
Copy code
    PApplet sketch = this;
    println(sketch);
    
this approach is quite longwinded, since my class is called from another class so I have to pass "this" on twice......
Sometimes it will be enough to just import processing.core.PApplet, there are a lot of static functions you can use without needing an object of PApplet (this).

sketch.pde
Copy code
  1. A a;

  2. void setup() {
  3.   a = new A();
  4.   a.doStuff();  
  5. }
A.pde
Copy code
  1. import processing.core.PApplet;

  2. public class A{
  3.    public void doStuff() {
  4.     PApplet.println("stuff");
  5.   }  
  6. }



This trick is useful in a .java file / tab, not necessary in a .pde tab (as A will be a class nested in the sketch class).
You're right, A.pde will work like this, too:
Copy code
  1. class A{
  2.   public void doStuff() {
  3.      println("stuff");
  4.      ellipse(50, 50, 50, 50);
  5.   }  
  6. }
Just wanted to show, that you can access static functions without a reference to the sketch.