javaScript问题关于;这";
我试图构建一个游戏恶魔,但在尝试向按钮添加ClickEventHander时遇到了一个问题,代码如下:javaScript问题关于;这";,javascript,Javascript,我试图构建一个游戏恶魔,但在尝试向按钮添加ClickEventHander时遇到了一个问题,代码如下: function GameConstructor(){ this.start = startGame; this.count = 5; ... function startGame(){ if(this.count > 5){ //here goes the problem, this don't point to the game obj
function GameConstructor(){
this.start = startGame;
this.count = 5;
...
function startGame(){
if(this.count > 5){ //here goes the problem, this don't point to the game object when I click the button
...
}
}
...
var game = new GameConstructor(); //game object has a method called start
$("#someBtn").click(game.start); //in the method start this now point to the button so this.count is undefined.
我知道我可以定义一个全局变量count=5来解决这个问题,但我只是想知道是否有一种方法可以用我原来的方法解决这个问题?谢谢。这始终指向Javascript中的当前函数上下文。表示“this”中最低的函数。所以,你可以这样做
function GameConstructor(){
var self= this;
this.start = startGame;
this.count = 5;
...
function startGame(){
if(self.count > 5){ //here goes the problem, this don't point to the game object when I click the button
...
}
}
...
var game = new GameConstructor(); //game object has a method called start
$("#someBtn").click(game.start); //in the method start this now point to the button so this.count is undefined.
我不是一个完整的JavaScript向导,但我猜嵌套函数中的
this
是指该嵌套函数,而不是外部实例
许多人选择创建一个self
变量,以更明确地描述这个范围。也许可以试试这个:
function GameConstructor(){
var self = this; // <-- here, then reference self subsequently
self.start = startGame;
self.count = 5;
...
function startGame(){
if(self.count > 5){ //here goes the problem, this don't point to the game object when I click the button
...
}
}
函数GameConstructor(){
var self=this;//5){//问题出在这里,当我单击按钮时,它不会指向游戏对象
...
}
}
在这种情况下,您无法访问父级。原因这是当前功能范围的上下文。使用var代替ES6?如果是,请使用箭头函数。使用此
将超出范围,您可以改为使用let
$(“#someBtn”)。单击(函数(){game.start())在jQuery单击事件中,code>或this.start=startName.bind(this)
this
指被单击的元素。this
几乎从不指函数。谢谢,它可以工作!我想知道是否有必要在每次构建构造函数时都创建一个“self”变量?@YuDuan-我发现这是一个很好的实践。对于许多人来说,它更容易理解和排除故障。有了这一点,许多更新的JS构造使这一点变得不那么重要,但是对于“传统”的JS代码,这是常见的,我认为它是一个更好的实践。@ JDL13467 9,所以在最坏的情况下,添加一个“自”变量不会损害您的代码,是正确的吗?我不认为<代码>这个< /代码>总是指向函数…它取决于调用上下文,对吗?这个
在jQuery点击事件中指的是点击的元素。gameCons
对于这个
的别名副本来说是一个可怕的名字。它是实例的别名,而不是构造函数。好了,伙计们,我想让OP不理解这个。谢谢-现在快乐吗??我自己做的