提问人:Chris 提问时间:2/3/2011 最后编辑:El RonnocoChris 更新时间:11/21/2019 访问量:147164
JavaScript 中的“var that = this;”是什么意思?
What does 'var that = this;' mean in JavaScript?
问:
在一个JavaScript文件中,我看到:
function Somefunction(){
var that = this;
...
}
声明并分配给它的目的是什么?that
this
答:
从 克罗克福德
按照惯例,我们将该变量设为私有。这用于使 私有对象可用 方法。这是 ECMAScript 语言中的错误 导致这种情况的规范 内部函数设置不正确。
function usesThis(name) {
this.myName = name;
function returnMe() {
return this; //scope is lost because of the inner function
}
return {
returnMe : returnMe
}
}
function usesThat(name) {
var that = this;
this.myName = name;
function returnMe() {
return that; //scope is baked in with 'that' to the "class"
}
return {
returnMe : returnMe
}
}
var usesthat = new usesThat('Dave');
var usesthis = new usesThis('John');
alert("UsesThat thinks it's called " + usesthat.returnMe().myName + '\r\n' +
"UsesThis thinks it's called " + usesthis.returnMe().myName);
这会提醒...
用途认为它叫戴夫
用途这认为它被称为未定义
评论
that
this
我将用一个插图来开始这个答案:
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证明了这一点,它只是略有不同:
$('#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
});
});
由于在通过调用新函数更改范围时会频繁更改,因此无法使用它访问原始值。将其别名化允许您仍能访问 的原始值。this
that
this
就个人而言,我不喜欢使用 作为别名。它所指的是什么很少是显而易见的,尤其是当函数超过几行时。我总是使用更具描述性的别名。在上面的例子中,我可能会使用 .that
clickedEl
评论
var self = this;
that
this
forEach
colours.forEach(function(){/* 'this' is bound correctly --> */}, this);
var that = this
forEach
这是一个使内部函数(在其他函数中定义的函数)更像它们应该的那样工作的技巧。在 javascript 中,当您在另一个函数中定义一个函数时,会自动设置为全局范围。这可能会造成混淆,因为您希望具有与外部函数中相同的值。this
this
var car = {};
car.starter = {};
car.start = function(){
var that = this;
// you can access car.starter inside this method with 'this'
this.starter.active = false;
var activateStarter = function(){
// 'this' now points to the global scope
// 'this.starter' is undefined, so we use 'that' instead.
that.starter.active = true;
// you could also use car.starter, but using 'that' gives
// us more consistency and flexibility
};
activateStarter();
};
当您将函数创建为对象的方法(如示例中)然后在该方法中创建函数(如 )时,这尤其是一个问题。在顶级方法中,指向对象,它是 的方法(在本例中为 ),但在内部函数中,它现在指向全局范围。这是一种痛苦。car.start
activateStarter
this
car
this
创建一个变量以在两个作用域中按约定使用是 javascript 这个非常普遍的问题的解决方案(尽管它在 jquery 函数中也很有用)。这就是为什么使用听起来非常笼统的名称的原因。这是一个易于识别的约定,用于克服语言中的缺点。that
就像El Ronnoco暗示的那样,道格拉斯·克罗克福德(Douglas Crockford)认为这是一个好主意。
评论
有时可以引用另一个作用域并引用其他内容,例如,假设您想在 DOM 事件中调用构造函数方法,在这种情况下将引用 DOM 元素而不是创建的对象。this
this
[HTML全文]
<button id="button">Alert Name</button>
JS系列
var Person = function(name) {
this.name = name;
var that = this;
this.sayHi = function() {
alert(that.name);
};
};
var ahmad = new Person('Ahmad');
var element = document.getElementById('button');
element.addEventListener('click', ahmad.sayHi); // => Ahmad
上面的解决方案将保证我们可以从 中访问方法中的 name 属性,因此可以在 DOM 调用中毫无问题地调用它。this
that
sayHi
that
另一种解决方案是分配一个空对象并向其添加属性和方法,然后返回它。但是使用这个解决方案,你失去了构造函数。that
prototype
var Person = function(name) {
var that = {};
that.name = name;
that.sayHi = function() {
alert(that.name);
};
return that;
};
如果您使用 or 进行解决方法,则实际上没有必要使用 :that
call()
apply()
var car = {};
car.starter = {};
car.start = function(){
this.starter.active = false;
var activateStarter = function(){
// 'this' now points to our main object
this.starter.active = true;
};
activateStarter.apply(this);
};
下面是一个示例 `
$(document).ready(function() {
var lastItem = null;
$(".our-work-group > p > a").click(function(e) {
e.preventDefault();
var item = $(this).html(); //Here value of "this" is ".our-work-group > p > a"
if (item == lastItem) {
lastItem = null;
$('.our-work-single-page').show();
} else {
lastItem = item;
$('.our-work-single-page').each(function() {
var imgAlt = $(this).find('img').attr('alt'); //Here value of "this" is '.our-work-single-page'.
if (imgAlt != item) {
$(this).hide();
} else {
$(this).show();
}
});
}
});
});`
因此,您可以看到 this 的值是两个不同的值,具体取决于您目标的 DOM 元素,但是当您将“that”添加到上面的代码中时,您将更改目标“this”的值。
`$(document).ready(function() {
var lastItem = null;
$(".our-work-group > p > a").click(function(e) {
e.preventDefault();
var item = $(this).html(); //Here value of "this" is ".our-work-group > p > a"
if (item == lastItem) {
lastItem = null;
var that = this;
$('.our-work-single-page').show();
} else {
lastItem = item;
$('.our-work-single-page').each(function() {
***$(that).css("background-color", "#ffe700");*** //Here value of "that" is ".our-work-group > p > a"....
var imgAlt = $(this).find('img').attr('alt');
if (imgAlt != item) {
$(this).hide();
} else {
$(this).show();
}
});
}
});
});`
.....$(that).css(“背景色”, “#ffe700”);这里 “that” 的值是 “.our-work-group > p > a”,因为 var 的值 = this;因此,即使我们在 “this”= '.our-work-single-page',我们仍然可以使用 “that” 来操作以前的 DOM 元素。
评论