so I'm having a problem with scope in javascript. I'm currently writing a little js app to allow me to create console-based(or looking) games on my website super quickly and have most of my utility and specific console-application functions stored within variables.
The problem occurs when I wanna add a "setTimeout" or Interval function and want to use my variable functions. I know about proxy but theres gotta be a better way than calling $.proxy every time I wanna refer to one of my functions, and calling proxy for everything im referring to WITHIN those functions.
jQuery(document).ready(function(){
let gameStart = $.proxy(game.start, game);
setTimeout(gameStart, 1000);
});
let options = {
"consoleOutputDiv":"#console-output",
"thisIsHowIFormatText":"something"
};
let utils = {
formattxt: function(str){
let formatted = str;
let toReplace = options.thisIsHowIFormatText;
//I need to refer to options.thisIsHowIFormatText now and thats not possible.
//format text here!
return formatted;
}
}
let consolApp = {
log: function(str){
let stringToBeLogged = str;
//ok so now I need to refer to formattxt which refers to options.thisIsHowIFormatText
let format = $.proxy(utils.formattxt, utils, str);
stringToBeLogged = format();
//print stringToBeLogged to my console div.
}
}
let game = {
start: function() {
let consol = $.proxy(consolApp.log, consolApp, 'please log me!');
consol();
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id='console-output'></div>
I just think there's gotta be a better way! That gets tedious and just looks gross to me constantly calling $.proxy everywhere to allow for my functions to work.