有没有更好的方法来将范围设置为全局变量函数?

时间:2019-04-15 16:51:33

标签: javascript jquery

所以我在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以允许我的功能正常工作。

1 个答案:

答案 0 :(得分:0)

以下是您的代码的一个OOP建议,也许刚好足以使您了解这种应用程序的结构方式:

  • 在加载窗口后,经过1秒钟的超时,将创建一个新游戏。
  • 游戏在启动时会创建一个控制台。
  • 控制台使用静态utils方法。

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)
})
相关问题