在一个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
作为别名.很难看出它指的是什么,特别是当函数超过几行时.I always使用更具描述性的别名.在上面的示例中,我可能会使用clickedEl
.