所以我对javascript的范围有问题。我目前正在编写一个小的js应用程序,允许我在我的网站上超级快地创建基于控制台(或查看)的游戏,并将我的大部分实用程序和特定的控制台应用程序功能存储在变量中。
当我想要添加一个"setTimeout“或Interval函数并想要使用我的变量函数时,就会出现这个问题。我知道代理,但总比每次我想要引用我的函数时调用$.proxy更好,并且为所有我在这些函数中引用的东西调用代理。
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>
我只是觉得一定有更好的办法!这很乏味,对我来说很恶心,经常打电话给$.proxy让我的函数能够工作。
发布于 2019-04-15 18:01:52
这里有一个针对您的代码的OOP小建议,可能足以让您了解这类应用程序的结构:
class Utils {
static format(str){
let formatted = str + "!!!"
return formatted;
}
}
class Console {
log(str){
let stringToBeLogged = Utils.format(str);
console.log(stringToBeLogged)
}
}
class Game {
start() {
let consol = new Console()
consol.log('please log me...');
}
}
window.addEventListener("load", () => {
setTimeout(()=>{
let g = new Game()
g.start()
}, 1000)
})https://stackoverflow.com/questions/55693926
复制相似问题