'var that = this;' 在 JavaScript 中是什么意思?
2022-08-29 23:34:06
在我看到的一个JavaScript文件中:
function Somefunction(){
var that = this;
...
}
声明和分配它的目的是什么?that
this
在我看到的一个JavaScript文件中:
function Somefunction(){
var that = this;
...
}
声明和分配它的目的是什么?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
从 克罗克福德
按照惯例,我们创建一个私有的变量。这用于使对象可供私有方法使用。这是 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);
此警报...
用途认为它被称为戴夫
用途这认为它被称为未定义