In p5.js, to call the setup function you simply write:
function setup() {
}
How did they make it so you call function
and then the name, instead of just saying the following?
setup();
In p5.js, to call the setup function you simply write:
function setup() {
}
How did they make it so you call function
and then the name, instead of just saying the following?
setup();
To use p5.js we don't call the setup
function. We define a setup
function that code inside of p5.js calls.
In the case where we have code that looks like this:
<script src="../p5/lib/p5.js"></script>
<script>
function setup() {
background(100, 0, 100);
}
</script>
Our setup
function is added to the global window object and can be called by code inside of p5.js. If we were running in instance mode, our setup
function would not be added directly to the window object, but p5.js would still be able to find it and call it.
For simplicity, let's focus on the case as above where we have written setup
and it is attached to the window object.
Looking at the p5.js source code, we see a function called _setup
and in that function this code:
if (typeof context.setup === 'function') {
context.setup();
}
This is where our setup
gets called. If we add this alert:
if (typeof context.setup === 'function') {
if (context === window)alert("context is window");
context.setup();
}
we can verify that the context object is indeed the window object and _setup
is calling the setup
function that we created in our code.