0

I know it’s usually better to answer these questions with a google search, but I can’t seem to find it anywhere online. I wrote a function for creating a GlowScript canvas and adding it to an inputted div. I based it off of the code given on the website with some changes. Here is the function (it won't run on here because you need to import libraries, but it does create a 3D shape and put it in the div):

make_box("my_div")
function make_box(my_div){
    window.__context = {glowscript_container: document.getElementById(my_div)}
    var scene = canvas();

    // create some shapes:
    box( {pos:vec(.25,-1.4,0), size:vec(4.8,.3,2.5), color:color.red} )  
}

I think the first line is required to add the canvas to the div. Without the line, I get the error:

Uncaught TypeError: Cannot set property ‘canvas_selected’ of undefined

I don’t really understand what it’s doing, however, and what the window context means. Does anyone have any insight into the line? Thanks!

doo_doo_fart_man
  • 394
  • 3
  • 11
  • What libraries are you using? –  Dec 11 '20 at 20:58
  • I'm using the libraries which are imported in the template GlowScript code. The first lines of the code in this sample GlowScript code show all the libraries imported: https://www.glowscript.org/#/user/GlowScriptDemos/folder/Examples-JavaScript/program/AtomicSolid/share – Ephraim Bryski Dec 12 '20 at 05:07

2 Answers2

1

This is what I found when I searched for window and context separately via google.

Apparently window is an object and .__context is a version of this. More information can be found in the links below.

https://www.w3schools.com/js/js_window.asp

https://towardsdatascience.com/javascript-context-this-keyword-9a78a19d5786

Dharman
  • 30,962
  • 25
  • 85
  • 135
Dan.db
  • 79
  • 6
0

window is a global object, that can be accessed by all script in a given page. Because of that, you have to be careful with it, and not use it for all sorts of stuff, because then your scripts will start tripping over each other, causing weird bugs and potential security holes.

In the wild west of javascript, people used global variables all the time, but this was bad, and techniques were developed to avoid it. This is one such technique, but perhaps not the best, since it is still globally accessible. So instead of creating a whole bunch of global variables, you create one variable, in this case __context, and use it as a bag for all your global stuff. The "__" in front denotes that it should be private, but that's just a hint, it's not enforced in any way.

Uncaught TypeError: Cannot set property ‘canvas_selected’ of undefined

The error message you are seeing is from somewhere else in the code, where the code is trying to put something in the bag. But the bag is not there, it's undefined.

MichaelRom
  • 174
  • 1
  • 8