Search code examples
javascriptreactjsp5.js

How does p5.js instance mode work where the argument to instantiate the object is a function?


I’m having issues understanding how the P5.js instance mode works. The syntax of creating the object seems so different from anything else I’ve seen.

We’re instantiating a new object with the ‘new p5(Sketch)’ statement in UseEffect. Usually to instantiate a new object, an argument is passed that has the necessary requirements for the Constructor in a Class to create. However, in this case, a new object is being instantiated by passing a function as an argument. This seems so different from what I’ve encountered in the past.

I can use these templates and have been able to create my own customized code. However, it bothers me that how this is so different.

I would like to understand the principles. Can someone please explain to me in a detailed manner?I’m a self-taught programmer and am able to code certain work or hobby related requirements. I’m familiar with OOP principles.

I understand the objective is to use the instance mode so that we don’t confuse the common variables/functions with other libraries.

I’ve tried to read as much possible but I’ve not understood the explanations. I had also tried https://github.com/processing/p5.js/wiki/Global-and-instance-mode

The two most confusing lines are:

  1. new p5(Sketch);
  2. const Sketch = p5 => {….}

Here are a few specific questions:

  1. We’re instantiating a p5 object with a function with the ‘new p5(Sketch’. How is this possible?
  2. The Sketch function itself has a p5 argument. So, we seem to be instantiating a p5 object with an argument Sketch which itself has a p5 object as an argument. This seems circular.
import React, { useEffect } from "react";
import * as p5 from "p5";
 
const P5Sketch = () => {
 const Sketch = p5 => {
   Let radius;  
   p5.setup = () => {
     p5.createCanvas(p5.windowWidth, p5.windowHeight);
     p5.background(0);
     Radius = 0;
   };
 
   p5.draw = () => {
    p5.ellipse(p5.width/2,p5.height/2,radius,radius);
      radius++;  
   };
 };
 
 useEffect(() => {
  new p5(Sketch);
 }, []);
 
 return (
    <></>
 );
};
 
export default P5Sketch;

I've tried to read as much as possible to understand this but not able to grasp it.


Solution

  • This is nothing unusual if you're accustomed to first-class functions in JS. Functions are the same as any other object--you can store them in variables and pass them as parameters. It's also common to use functions in JS as namespaces, to close over a set of variables. Both principles are at play here.

    The Sketch function is a closure and p5.js calls it with the instance it's created passed as a parameter. You then add the draw/setup callbacks to the instance within the closure as you see fit.

    There's nothing circular here because the p5 parameter name replaces the p5 declared in the outer scope within the Sketch function. You can make that parameter any name you want. p is a common variant.

    Similarly, Sketch is a poor variable name because functions are lowerCamelCase by convention. p5 should be P5 as well since it's a class, and classes are UpperPascalCase.

    You can code this up yourself if you want to assist understanding:

    class P5 {
      constructor(sketchFunction) {
        const p5Instance = {};
        sketchFunction(p5Instance);
        p5Instance.setup?.();
    
        if (p5Instance.draw) {
          (function update() {
            requestAnimationFrame(update);
            p5Instance.draw();
          })();
        }
      }
    }
    
    const sketchClosure = (p5Instance) => {
      let ticks = 0;
    
      p5Instance.setup = () => {
        console.log("setup!");
      };
    
      p5Instance.draw = () => {
        console.log(`draw! ${ticks++}`);
      };
    };
    
    new P5(sketchClosure);

    This is a contrived, simplified example of what p5 does and not to be used for anything other than this demonstration.

    Although it might be more confusing, p5 is probably doing something a bit more like this, which lets you use the return value from the constructor as another copy of the instance:

    class P5 {
      constructor(sketchFunction) {
        sketchFunction(this);
        this.setup?.();
    
        if (this.draw) {
          const update = () => {
            requestAnimationFrame(update);
            this.draw();
          };
          update();
        }
      }
    }
    
    const sketchClosure = (p5Instance) => {
      let ticks = 0;
    
      p5Instance.setup = () => {
        console.log("setup!");
      };
    };
    
    const myInstance = new P5(sketchClosure);
    console.log(!!myInstance.setup); // true

    Other issues in your code:

    • Radius = 0 should be radius = 0
    • Let radius needs to be let radius

    See also the Instance Mode (aka "namespacing") Coding Train video.