this.async()在JavaScript中做什么 [英] What does this.async() do in JavaScript
问题描述
继续在代码中看到这种模式,但是在google或SO中找不到对该模式的任何引用,这很奇怪.有人可以指出我要参考的this.async()函数吗?
Kept on seeing this pattern in code, but couldn't find any reference to it in google or SO, strange. Can someone point me to reference for this.async() function?
var done = this.async();
// ...
$.get(path, function(contents) { // or some other function with callback
// ...
done(JST[path] = tmpl);
})
推荐答案
这是解决this
在回调内部转义的方法.没有此额外参考,代码将如下所示:
It is a way to work around the problem of this
escaping inside callback. Without this extra reference the code would look like this:
$.get(path, function(contents) { // or some other function with callback
//Wrong! `this` might no longer point to your object
this.done(JST[path] = tmpl);
})
不幸的是!响应回调内部的this
与外部的this
不同.实际上,它可以是任何东西,具体取决于$.get
(使用调用回调)决定它是什么.大多数人出于相同目的使用名为that
的额外引用:
Unfortunately! this
inside response callback is not the same as this
outside of it. In fact it can be anything, depending on what $.get
(calling the callback using) decides it to be. Most of the people use extra reference named that
for the same purpose:
var that = this;
// ...
$.get(path, function(contents) { // or some other function with callback
// ...
that.async(JST[path] = tmpl);
})
这种模式似乎也是合理且可读的.
This pattern also seems reasonable and readable.
哦,如果您对此语法感到好奇:
Oh, and if you are curious about this syntax:
done(JST[path] = tmpl)
这是一个用作表达式的赋值.赋值的值在右侧,因此此代码等效于:
This is an assignment used as an expression. The value of assignment is the right-hand side, so this code is equivalent to:
JST[path] = tmpl;
done(tmpl);
这篇关于this.async()在JavaScript中做什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!