您的位置:首页 > Web前端 > JavaScript

What does var that = this; mean in javascript?

2015-01-16 10:41 417 查看
[b]Question:[/b]

In a javascript file I saw:

function Somfunction(){
var that = this;
...
}


What does this do precisely?

Answer1:

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
});
});


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
.

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
.

Answer2:

By convention, we make a private that variable. This is used to make the object available to the private methods. This is a workaround for an error in the ECMAScript Language Specification which causes this to be set incorrectly for inner functions.

……………………………………

【转载】http://stackoverflow.com/questions/4886632/what-does-var-that-this-mean-in-javascript
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: