scope - Javascript: append script with an object, and create a local instance -
let me expose question: have main script, let's creates instance of "game" object, which, depending on actions of user, loads 1 of many javascript files, let's call them "levels" :d these files contains different objects, example, "level1.js" contains object level1, "level2.js", etc.
each time level script loaded, example level1.js, instance of "game" creates instance of object level1 , stores in local variable.
the way i've found it, write, @ end of "level" scripts, global variable, has same name, , points definition of current level. in game, when level script loaded, use global variable create instance of current level. know if there way without using global variable.
here simplified example:
in game.js:
function game() { var levelcurrent = null; var scriptcour = document.createelement("script"); scriptcur.type = "text/javascript"; scriptcur.onload = function() { levelcurrent = new level(); } } and in each "level" script (level1.js, level2.js):
function level1() { //definition of level //... } level = level1; or, similarly:
level = function() { //definition of level //... } i don't know if explained enough question, if has answer... thank you! note instance of game created using self-executing function, , therefore local variable, like:
(function() { var game = new game(); })(); thank you!
instead of assigning new level global variable, should call global function level information, e.g.
window.addlevel(function level1() { //definition of level //... }); why game instance local variable, can't accessed? guess it's singleton (only 1 instance), valid have global variable. namespace addlevel function (window.game.addlevel()).
Comments
Post a Comment