Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

ProcessingJS ‘this’ Keyword: How Does it Work?

Learn how the ‘this’ keyword works in ProcessingJS. Understand object context and coding patterns with real examples for better learning.
Confused developer struggles with 'this' keyword in ProcessingJS vs happy developer running successful canvas code Confused developer struggles with 'this' keyword in ProcessingJS vs happy developer running successful canvas code
  • ⚠️ In ProcessingJS, the this keyword often changes context without warning, especially inside timer callbacks or event functions.
  • 🧠 ProcessingJS puts JavaScript into global scope structures. This affects how this acts inside object methods you write.
  • 💡 Arrow functions and .bind() are good ways to control this in functions that run later or respond to events.
  • 🧰 Developers often run into this problems in mouse events, loops, and time-based animations. They must manage context clearly.
  • 👩‍🏫 Students and beginners usually misunderstand object method context. This causes undefined errors or wrong behavior.

The JavaScript this Keyword

The this keyword in JavaScript changes. Its value depends on how you call a function, not where the function is written. When people do not understand this, they often get frustrated and find their code hard to fix. This is especially true for new programmers or those coming from languages like Python, Java, or C++.

How to Use this with Object Methods

When you make a function inside an object, and then call it using that object (like object.method()), this points to that object:

let shape = {
  name: "circle",
  describe: function() {
    console.log(this.name); // 'this' points to `shape`, it shows "circle"
  }
};

shape.describe(); // Output: "circle"

What Happens When You Take a Function Out of an Object

If you put a method into another variable and then run it:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

let standalone = shape.describe;
standalone(); // Output: undefined or a global object, NOT "circle"

Here, this no longer points to shape. This is because the function is not called by the object anymore. In strict mode, this becomes undefined. Without strict mode, it points to the global object, like window in browsers. This can cause small problems that only appear when your program runs.

This behavior creates more trouble in things like setTimeout, DOM event handlers, or framework hooks. These often disconnect functions from their original context. So, this loses the value you expected.


What ProcessingJS Is

ProcessingJS is a visual programming system. It came from the popular Processing language, which is based on Java, but now runs in JavaScript. It lets people write code that works with the HTML5 Canvas. It uses simple ways to draw things, like what you find in Java or openFrameworks.

Some things you get with ProcessingJS:

  • A simple way to draw shapes (like ellipse(), line(), rect(), and more).
  • Animations run using setup() and draw() functions.
  • It also supports object-oriented ways to design code.
  • It has ready-to-use ways to handle mouse events, for example mousePressed() and mouseMoved().

The ProcessingJS system hides many of JavaScript's small details. This is good because it makes the system easier to use. But, this can also make people think wrongly about where and how code runs. This happens a lot when working with basic JavaScript parts like this.


How this Acts Differently in ProcessingJS

In regular JavaScript, this is connected to how you call the function. But in ProcessingJS, especially in its main drawing area, the code you write might get put inside other objects or functions when ProcessingJS runs it.

This means a few things:

  • Global variables might change where they can be used.
  • Functions inside draw(), setup(), or mouse events might stop pointing to their object.
  • Your object-oriented code might not work well with how ProcessingJS handles events inside.

Object-oriented JavaScript lets you put actions and data together. But, ProcessingJS does not always keep this as you would think. This happens when those objects work with the drawing loops or functions that run later, such as setTimeout() or event handlers.


Making ProcessingJS Objects: this at Work

Let’s make a shape object we can use many times. Then we can see how this acts the right way:

function Shape(x, y) {
  this.x = x;
  this.y = y;
  
  this.display = function() {
    ellipse(this.x, this.y, 50, 50); // Uses the object’s own numbers
  };
}

let s = new Shape(100, 100);

draw = function() {
  background(255);
  s.display(); // Here, `this` points to the Shape object, which is correct.
};

In this example:

  • The Shape setup function uses this.x and this.y to keep track of where the shape is.
  • We call the display() method through s, which is a Shape object.
  • JavaScript makes sure this inside display() points to s in the right way.

When you call methods right away, like s.display(), this keeps its correct meaning.


How this Breaks When Using Callback Functions in ProcessingJS

Problems often come up when you use object methods by themselves as functions that run later. JavaScript's way of running functions takes away the this context unless you clearly save it.

Example: this Gets Lost with setTimeout

function Shape(x, y) {
  this.x = x;
  this.y = y;
  
  this.display = function() {
    ellipse(this.x, this.y, 50, 50);
  };
}

let s = new Shape(100, 100);
setTimeout(s.display, 1000); // ERROR: this.x is undefined

Why does this go wrong?

  • When you give s.display to setTimeout, it just becomes a normal function.
  • The link to s is broken.
  • Inside display(), this does not point to s anymore. Instead, it points to the global area (or is undefined).

This is confusing for new programmers. It causes problems when the program runs, and these problems are hard to find. Reas and Fry (2015) point out that many students in creative coding wrongly think this will always stay linked to where they wrote the function.


How to Fix this: Ways to Control Context

There are two good ways to stop this problems in JavaScript and ProcessingJS:

1. Use Arrow Functions

Arrow functions automatically take this from the code around them. This means if this points to something outside the function, it will still point to that inside.

setTimeout(() => s.display(), 1000); // Correct: `this` points to s

This way is neater. It also stops the common problems with how normal functions handle this. It is often better for timed animations or mouse events. This is because it is very important to keep the connection to the object's data.

2. Use .bind() to Make this Stick

You can clearly connect this using the .bind() method:

setTimeout(s.display.bind(s), 1000); // This also works

.bind() makes a new function where this always points to the value you give it. This is a strong method in object-oriented JavaScript.

Flanagan (2020) said it well: “.bind() is a smart way to stop this from acting weird when code runs out of order.”


Making Buttons and Other UI Parts: Mouse Events and this

Here is a complete example sketch of a Button object in ProcessingJS. It works right when you click the mouse:

function Button(x, y) {
  this.x = x;
  this.y = y;
  this.clicked = false;

  this.display = function() {
    fill(this.clicked ? 'green' : 'red');
    rect(this.x, this.y, 100, 50);
  };

  this.handleClick = () => {
    if (mouseX > this.x && mouseX < this.x + 100 &&
        mouseY > this.y && mouseY < this.y + 50) {
      this.clicked = !this.clicked;
    }
  };
}

let btn = new Button(150, 100);

mousePressed = function() {
  btn.handleClick(); // This works right because we used an arrow function.
};

draw = function() {
  background(255);
  btn.display();
};

In this sketch:

  • We set this.handleClick as an arrow function.
  • And then, even when it is called inside the global mousePressed handler, this still points correctly to the button.

If you did not use an arrow function, this might point to the global object inside handleClick(). This would break your if statements and how your user interface responds.


Fixing this Problems in ProcessingJS Sketches

When this causes problems, try these steps:

  • Put console.log(this) inside the function. This will show you what this points to when the function runs.
  • And then, check where and how you call the method.
  • Wrap function calls with arrow functions or use .bind().
  • Also, keep who owns what clear in your code's structure (object to method).

Knowing how to tell when this is wrong saves a lot of time fixing code.


Problems with Functions Inside Other Functions in ProcessingJS

Normal functions written inside other functions do not get this from their parent function. Look at this example:

this.update = function() {
  setTimeout(function() {
    console.log(this); // Wrong: global or undefined
  }, 1000);
};

Fix it like this with an arrow function:

this.update = function() {
  setTimeout(() => {
    console.log(this); // Correct: `this` gets taken from the outside function
  }, 1000);
};

Functions inside other functions are often where this acts in ways you do not expect.


Using draw() and the Main Program Loop

The draw() method is very important for ProcessingJS sketches. It makes the animation run over and over, 60 times each second, normally.

Simple shapes and variables are fine for small drawings. But, if you want to make bigger projects, you need a clear way to organize things:

let shapes = [];

function Circle(x, y) {
  this.x = x;
  this.y = y;

  this.show = function() {
    ellipse(this.x, this.y, 30, 30);
  };
}

setup = function() {
  for (let i = 0; i < 5; i++) {
    shapes.push(new Circle(60 * i + 30, 200));
  }
};

draw = function() {
  background(255);
  for (let s of shapes) {
    s.show(); // Here, `this` is correct.
  }
};

By keeping objects and their method calls separate, you stop problems with this.


Animating with this: How Real Projects Are Set Up

Let’s make an animation system we can use many times, built with objects:

function Ball(x, y, speed) {
  this.x = x;
  this.y = y;
  this.speed = speed;

  this.update = function() {
    this.x += this.speed;
    if (this.x > width) this.x = 0;
  };

  this.display = function() {
    ellipse(this.x, this.y, 20, 20);
  };
}

let balls = [
  new Ball(0, 100, 2),
  new Ball(0, 150, 3)
];

draw = function() {
  background(255);
  for (let b of balls) {
    b.update();
    b.display();
  }
};

Each ball handles its own data and changes itself. This makes sure it always acts the same way. There is no confusion about what this points to here.


Good Design: How to Stop this Problems Entirely

A few simple ways to design code make it easier to guess what it will do:

  • Use arrow functions when this is needed inside another function.
  • Always call methods using the object that owns them.
  • And then, use .bind() if you give functions to other parts of your code.
  • Do not put normal functions inside objects, unless you control this yourself.

Making your code clearer stops confusion about this. It also helps you make parts you can use again.


Beginner Mistakes with this in ProcessingJS

In classrooms and on the internet, new programmers often:

  • Use this outside the object it was meant for.
  • Think this points to the object where they wrote the function. But, it actually points to how they call it.
  • Give method names as functions to run later, without using .bind().
  • Write functions that run after a time or on an event without care. This causes undefined errors that are hard to see.

Showing programmers to think about how functions are called makes things smoother. It also gets better results.


A Last Word: Understand JavaScript this in ProcessingJS

When you understand how the JavaScript this keyword acts, and how it acts differently in places like ProcessingJS, you can make clear animations, well-built programs, and interfaces that respond well.

The biggest mistake is not using this. It is thinking this always means the same thing.

If you know about how variables are found, use tools like arrow functions and .bind(), and pay attention to how you call methods, you can build any creative coding project. It will act the same way across objects, loops, and user actions.

Want to learn more? Look at these other guides:

Happy coding!


References

  • Mozilla Developer Network. (n.d.). this – JavaScript | MDN.
  • Reas, C., & Fry, B. (2015). Getting Started with p5.js. O’Reilly Media.
  • Flanagan, D. (2020). JavaScript: The Definitive Guide (7th ed.). O’Reilly.
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading