js 中var that=this

时间:2021-11-16 10:04:08

js中经常出现var that=this,为什么这么做?

http://*.com/questions/4886632/what-does-var-that-this-mean-in-javascript

问题,回答:

一个回答:
$('#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.

另一个回答:From Crockford

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.