什么'var that = this;'用JavaScript表示? [英] What does 'var that = this;' mean in JavaScript?
问题描述
在我看到的JavaScript文件中:
In a JavaScript file I saw:
function Somefunction(){
var that = this;
...
}
声明<$ c的目的是什么$ c>那并将其分配给这个
?
推荐答案
我将以插图的方式开始这个答案:
I'm going to begin this answer with an illustration:
var colours = ['red', 'green', 'blue'];
document.getElementById('element').addEventListener('click', function() {
// this is a reference to the element clicked on
var that = this;
colours.forEach(function() {
// this is undefined
// that is a reference to the element clicked on
});
});
我的回答最初用jQuery证明了这一点,只是略有不同:
My answer originally demonstrated this with jQuery, which is only very slightly different:
$('#element').click(function(){
// this is a reference to the element clicked on
var that = this;
$('.elements').each(function(){
// this is a reference to the current element in the loop
// that is still a reference to the element clicked on
});
});
因为这个
经常在你改变时改变通过调用新函数的范围,您无法使用它来访问原始值。将其别名为,
允许您仍然可以访问的原始值
。
Because this
frequently changes when you change the scope by calling a new function, you can't access the original value by using it. Aliasing it to that
allows you still to access the original value of this
.
就个人而言,我不喜欢使用那个
作为别名。很少有人明白它的含义,特别是如果函数长于几行。我总是使用更具描述性的别名。在上面的例子中,我可能会使用 clickedEl
。
Personally, I dislike the use of that
as the alias. It is rarely obvious what it is referring to, especially if the functions are longer than a couple of lines. I always use a more descriptive alias. In my examples above, I'd probably use clickedEl
.
这篇关于什么'var that = this;'用JavaScript表示?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!