[英]Why does “this.myFunction” not work when calling a function inside an object?
Here are two samples of code.这是两个代码示例。 The first one does not work and the second one does, though I'm completely at a loss as to why.
第一个不起作用,第二个起作用,尽管我完全不知道为什么。 Can someone explain this?
有人可以解释一下吗?
[I'm writing a simple game using a bit of jQuery to be played in a webkit browser (packaged with Titanium later).] [我正在编写一个简单的游戏,使用一点 jQuery 在 webkit 浏览器中播放(稍后与 Titanium 一起打包)。]
In the first example, Firebug tells me that "this.checkCloud" is not a function.在第一个示例中,Firebug 告诉我“this.checkCloud”不是 function。
function Cloud(){
this.checkCloud = function(){
alert('test');
}
$("#"+this.cloudName).click(function(){
this.checkCloud();
});
}
...but then this works: ...但是这有效:
function Cloud(){
this.checkCloud = function(){
alert('test');
}
var _this = this;
$("#"+this.cloudName).click(function(){
_this.checkCloud();
});
}
This one works perfect.这个完美。
Why does the first one not work?为什么第一个不起作用? Is it because "this.checkCloud" is inside of the anonymous function?
是因为“this.checkCloud”在匿名 function 内部吗?
That is because the meaning of this
can potentially change each time you create a new scope via a function.这是因为每次您通过 function 创建新的 scope 时,其含义
this
会发生变化。 The meaning of this
depends on how the function is invoked (and the rules can be insanely complicated).其含义取决于
this
调用 function(并且规则可能非常复杂)。 As you discovered, the easy solution is to create a second variable to which you save this
in the scope where this
has the expected/desired value, and then reuse the variable rather than this
to refer to the same object in new function scopes where this
could be different.正如您所发现的,简单的解决方案是创建第二个变量,将其保存在 scope 中
this
this
具有预期/所需值,然后重用该变量而不是this
变量以在新 ZC1C425268E68385D1AB504 范围内引用相同的this
可能会有所不同。
in this example:在这个例子中:
$("#"+this.cloudName).click(function(){
this.checkCloud();
});
this
referrers to the element selected(jquery object). this
指向所选元素(jquery 对象)。
what you can do is use private functions你可以做的是使用私有函数
var checkCloud = function(){
alert('test');
}
this way you can simply call it inside your anonymous function这样你就可以简单地在你的匿名 function 中调用它
$("#"+this.cloudName).click(function(){
checkCloud();
});
Try this:尝试这个:
function Cloud(){
this.checkCloud = function(){
alert('test');
}
var func = this.checkCloud;
$("#" + this.cloudName).click(function(){
func();
});
}
When you assign an even listener to an element, jQuery makes sure that this
will refer to the element.当您为元素分配偶数侦听器时,jQuery 确保
this
将引用该元素。 But when you create the _this
variable, you're creating a closure that jQuery couldn't mess with, even if it wanted to.但是,当您创建
_this
变量时,您正在创建一个 jQuery 无法处理的闭包,即使它想要这样做。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.