I’ve come across two ways of defining classes in p5.js.
The first: https://editor.p5js.org/femkeblanco/sketches/Vycw0YkNr
The second: https://editor.p5js.org/femkeblanco/sketches/YXi8pCrRQ
I presume the second way, which I came across in the book “Getting Started with p5.js”, is legacy. Is that correct?
My main question is the following:
I cannot declare and create an object in one line at the top using the first way: https://editor.p5js.org/femkeblanco/sketches/f7xH0mqRX
I have to create the object in setup(): https://editor.p5js.org/femkeblanco/sketches/Vycw0YkNr
But I can declare and create an object in one line at the top using the second way: https://editor.p5js.org/femkeblanco/sketches/YXi8pCrRQ
Why, why and why?
Your help is appreciated and thanks in advance.
2 Likes
femke.blanco:
Why, why and why?
JS got 6 keywords that can be used to declare variables:
var
-> Developer.Mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var
function
-> Developer.Mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function
let
-> Developer.Mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let
const
-> Developer.Mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const
class
-> Developer.Mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/class
import
-> Developer.Mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import
Outta those 6 declaration keywords, the primeval 1s var
& function
, which existed since the very beginning of JS, got an exotic behavior called hoisting:
Variables declared via var
or function
already exist from the top, even when they’re declared much further down!
For a more detailed explanation about hoisting, go to the article’s link below:
2ality-com.OnRender.com/2019/05/unpacking-hoisting.html
Given keyword class
doesn’t hoist like function
does, as a workaround, move the whole class
to the top, before it’s used by anything else.
4 Likes