Skip to content

Instantly share code, notes, and snippets.

@mattdesl
Created March 2, 2020 17:43
Show Gist options
  • Save mattdesl/bd7a2c068f81d00285b31bb2134acda2 to your computer and use it in GitHub Desktop.
Save mattdesl/bd7a2c068f81d00285b31bb2134acda2 to your computer and use it in GitHub Desktop.

global vs instance mode

Details:
https://github.com/processing/p5.js/wiki/Global-and-instance-mode

I usually teach with 'global' mode as it is a bit simpler and easier to jump into, but it can encourage poor practices and lead to some headaches.

Here's a few things to be mindful of:

  • Common JavaScript features like cos() and PI become built-in globals, when a student transitions to other ecosystems (e.g. ThreeJS or even just Node.js) they have to re-learn which functions are builtin (e.g. setTimeout) and which are namespaced (Math.PI)
  • It forces variables to be defined in setup() as these globals don't exist yet (see here)
  • "Polluting the global namespace" is a really poor practice for JS libraries and is very heavily discouraged within the JS ecosystem, so teaching p5js in this way seems to implicitly suggest it is an acceptable design. (FWIW it is understandable that p5.js approached the library in this way, as it is designed to transition developers from Processing to JS with a nearly 1:1 mapping.)
  • Global mode generally doesn't play well with other libraries/ecosystems and doesn't produce very modular code
  • Global mode doesn't work with type="module" (ES modules) without manually adding p5 functions to the window scope

alternative

I'm thinking about teaching with 'instance' mode in future workshops. It looks like this:

https://glitch.com/edit/#!/p5-instance-mode?path=sketch.js

The benefits:

  • The code is more reusable, so you can take the same function and apply it to multiple p5 instances at the same time, or even use it across multiple p5 offscreen graphics
  • The code does not pollute global namespace or expect anything on the global namespace (except the initial p5 constructor)
  • This approach supports ES imports and exports out of the box so students can begin to learn how to split up their programs into chunks
  • Students learn things like Math.PI and Math.min (JS friendly) instead of p5 builtins (not JS friendly)
  • Students won't run into problems like random() not being set yet, because all of their code should be encapsulated within a closure

However, there are some downsides to this approach too. You can see it includes more boilerplate and may be more difficult for new students.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment