2016-03-06 103 views
0

遇到问题 - 我应该是 - 基本范围基础知识。 我使用的Javascript要求JS结构,这里是哪里出现问题:Js/Jquery中的变量范围问题

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 succefully所以我想使用this.game相同的方式,但它不工作。我可以设法通过直接使用$(“#游戏”),但它使得jquery每次运行通过DOM,所以没有真正优化...

我肯定缺少一些基本点在这里,有人可以解释一下吗?

谢谢

+1

你在哪里创建了'GameManager'的对象? –

+0

不确定要理解这个问题。我没有在那里使用对象。 – GreatHawkeye

+0

好的,你在哪里使用这段代码? 'var something = new GameManager();' –

回答

0

这是为我工作。我可以在没有问题的情况下从div中移除display-none类。它不会显示。你需要改变CSS。 this.body.css( “显示”, “块”);例如。

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(); 
}