首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >是否有更好的方法来设置全局变量函数的范围?

是否有更好的方法来设置全局变量函数的范围?
EN

Stack Overflow用户
提问于 2019-04-15 16:51:32
回答 1查看 51关注 0票数 0

所以我对javascript的范围有问题。我目前正在编写一个小的js应用程序,允许我在我的网站上超级快地创建基于控制台(或查看)的游戏,并将我的大部分实用程序和特定的控制台应用程序功能存储在变量中。

当我想要添加一个"setTimeout“或Interval函数并想要使用我的变量函数时,就会出现这个问题。我知道代理,但总比每次我想要引用我的函数时调用$.proxy更好,并且为所有我在这些函数中引用的东西调用代理。

代码语言:javascript
复制
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();
  }
}
代码语言:javascript
复制
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id='console-output'></div>

我只是觉得一定有更好的办法!这很乏味,对我来说很恶心,经常打电话给$.proxy让我的函数能够工作。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-04-15 18:01:52

这里有一个针对您的代码的OOP小建议,可能足以让您了解这类应用程序的结构:

  • 加载窗口时,在1秒超时后,将创建一个新游戏。
  • 游戏启动时会创建一个控制台。
  • 控制台使用静态utils方法。
代码语言:javascript
复制
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)
})
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55693926

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档