在回调函数中访问变量......什么? [英] Accessing variable in callback function... what?
问题描述
我经历了大量的帖子,我终于得到了我需要的东西,这要归功于:
I've been through a ton of posts and I finally got what I needed thanks to this:
$("a.foo").click(function(){
var that = this;
jPrompt("Type something:","","", function(r) {
$(that).text(r);
}
}
来自以下:
在回调函数中访问$(this)
我想知道是否有人可以扩展这里到底发生了什么(为什么这个
没有重新分配? )我应该阅读哪些核心信息?从我收集的内容中,这可能与封闭有关...这是我在搜索时遇到的大部分内容。这是准确的吗?
I was wondering if someone could expand on what exactly is happening here (why is this
not available without re-assigning?) and what core information I should read up on? From what I gather this might have something to do with closures... that's most of what I bumped into while searching around. Is that accurate?
在我的情况下,我想要执行一些代码,然后在ajax请求完成后重定向。在回调函数中,我运行 $(this).attr(href)
返回未定义。
In my case, I was looking to execute some code, then redirect once an ajax request completed. In the callback function I was running $(this).attr("href")
which was returning undefined.
推荐答案
此
根据函数的调用方式由javascript分配。因此, jPrompt()
函数确定在<$ c $>
中的值 c> jPrompt()
调用回调。
this
is assigned by javascript according to how a function is called. So, it is the jPrompt()
function that determines what value this
will have in your callback when jPrompt()
calls the callback.
所以,除非jPrompt通过你输入的一些参数来阻止这个
的相同值,它可能会有不同的价值。因此,您可以将其保存,以便在回调中进行访问。这是javacscript回调中非常常见的设计模式。
So, unless jPrompt goes out of its way to keep the same value for this
via some argument you passed in, it will likely have a different value. As such, you can save it away for access within the callback as you've done. This is a very common design pattern in javacscript callbacks.
仅供参考,分配了此
的一些方法:
FYI, some of the ways that this
is assigned:
-
obj.method()
-this
in方法()
将设置为obj
-
func.call(obj)
-此
infunc()
将设置为obj
-
func()
-此
将在func()
或<$中设置为窗口
c $ c>未定义严格模式
obj.method()
-this
inmethod()
will be set toobj
func.call(obj)
-this
infunc()
will be set toobj
func()
-this
will be set towindow
infunc()
orundefined
in strict mode
这篇关于在回调函数中访问变量......什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!