Is object creation delayed when managed into a P5js instance?

As my knowledge of JS is extremely limited, I cannot properly describe the issue: it is more a curiosity than a real problem (it took me some time to pinpoint it).

Here I am creating 2 objects, setting the type variable ONLY AFTER calling the object creation. It looks like the object is not created immediately but only in a second time, after the variable has been set, even if the lines order would hint otherwise.

Is this JS or P5.js related? Is this due to hoisting?

I would like, for my own knowledge, to be directed to the proper docs in order to understand what is happening here. Thanks

<html>
<head>
    <script type="text/javascript" src="static/js/p5.min.js"></script>
</head>
<body>
    <script>
        let sketch = function (p) {
            p.setup = function () {
                alert("Creating " + p.type);
            };
        };

        let objA = new p5(sketch);
        objA.type = "A";      // <--- AFTER creating the object?!?

        let objB = new p5(sketch);
        objB.type = "B";
    </script>
</body>
</html>

Answers

  • edited May 7 Answer ✓
    let sketch = function (p) {
        p.setup = function () {
            alert("Creating " + p.type);
        };
    };
    
    let objA = new p5(sketch);
    console.log(objA.type); // undefined
    objA.type = "A";
    
    let objB = new p5(sketch);
    console.log(objB.type); // undefined
    objB.type = "B";
    
  • edited May 7 Answer ✓
    • The sketch variable is passed to p5's constructor as a callback.
    • In order to know when that callback is actually invoked, we'd need to study p5.js' source code.
    • Also notice that setup() is a callback of the sketch callback.
    • Until the execution reaches the alert() inside setup(), the property type had been assigned to "A" a long time ago.
  • Thank you, @GoToLoop! I thought I was missing something very important about Javascript.

  • edited May 8 Answer ✓

    Is this due to hoisting?

    Hoisting only works for variables declared w/ keywords var & function. :-B
    Given type isn't even a variable but an object property, hoisting isn't applied to it in any case. :\">

Sign In or Register to comment.