【问题标题】:Issue with variables scope in Js/JqueryJs/Jquery 中的变量范围问题
【发布时间】:2016-03-06 21:11:44
【问题描述】:

有问题 - 我应该是 - basics 范围基础。 我正在使用带有 Require JS 结构的 Javascript,这里是出现问题的地方:

function GameManager() {
    //This is the constructor of gamemanager.js file
    this.body = $('body');
    this.game = $('#game');
}

GameManager.prototype.createGame = function() {

    //Code

    //this line works
    this.body.append(//Some HTML);
}

GameManager.prototype.showGame = function() {
    //Code

    //this line does not work wtf
    this.game.removeClass("display-none");
    //and this one does work.
    $("#game").removeClass("display-none");
}

我成功地使用了 this.body,所以我想对 this.game 使用相同的方式,但它不起作用。我可以通过直接使用 $("#game") 来使其工作,但它使 jquery 每次都在 DOM 中运行,所以没有真正优化......

我当然在这里遗漏了一些基本点,有人可以解释一下吗?

谢谢

【问题讨论】:

  • 你在哪里为GameManager创建了对象?
  • 不确定是否理解问题。我没有在那里使用对象。
  • 好的,你在哪里使用了这个 sn-p? var something = new GameManager();
  • @GreatHawkeye 我认为他要求确保在加载 DOM 后创建 GameManager。
  • @RajaprabhuAravindasamy,我在他的 init() 函数的 main.js 文件中创建实例。这是我使用的第一个函数!

标签: javascript jquery scope requirejs


【解决方案1】:

这对我有用。我可以毫无问题地从 div 中删除 display-none 类。但是它不会显示。你需要改变css。 this.body.css("display","block");例如。

window.onload = function() {

function GameManager() {
    //This is the constructor of gamemanager.js file
    this.body = $('body');
    this.game = $('#game');
}

GameManager.prototype.createGame = function() {

    //Code

    //this line works
    this.body.append();
}

GameManager.prototype.showGame = function() {
    //Code

    this.body.css("display", "block");
    //this line does not work wtf
    this.game.removeClass("display-none");
    //and this one does work.
    //$("#game").removeClass("display-none");
}


var myGame = new GameManager();
myGame.showGame();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-12
    • 2016-12-18
    • 2010-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多