我将以一个插图开始这个答案:
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。
就个人而言,我不喜欢使用
thatas作为别名。它指的是什么几乎是不明显的,特别是如果函数长于几行。我 总是
使用更具描述性的别名。在上面的示例中,我可能会使用
clickedEl。



