JSFiddle - React, Tailwind, and code Playground

by Josh Pullen

JavaScript

// We simulate importing scripts by running immediately-invoked functions

// import ScratchJS from "somewhere fun"
const ScratchJS = (function() {
  return {
    Sprite: class Sprite {},
    Stage: class Stage {
      constructor() {
        this.sprites = []
      }
      add(sprite) {
        this.sprites.push(sprite)
      }
      runProject() {
        this.greenFlag()
        for (const sprite of this.sprites) {
          sprite.greenFlag()
        }
      }
    }
  }
})()

// ./Stage/Stage.mjs
const Stage = (function(){
	class Stage extends ScratchJS.Stage {
    greenFlag() {
      console.log("From the stage: ", myCoolGlobalVar)
      
      // Error:
      // console.log("I, the stage, do not know that the cat says", myCoolSpriteVar)
    }
  }
  
  // export default Stage
  return Stage
})()

// ./Cat/Cat.mjs
const Cat = (function(){
	var myCoolSpriteVar = "meow"
  
  class Cat extends ScratchJS.Sprite {
    greenFlag() {
      console.log("From a cat:", myCoolGlobalVar)
      console.log("I, the cat, know all about the stage!", stage)
      console.log("I, the cat, say", myCoolSpriteVar)
    }
  }
  
  // export default Cat
  return Cat
})()

// ./index.mjs
let myCoolGlobalVar = 5
const stage = new Stage()

const cat = new Cat()
stage.add(cat)

stage.runProject()