关闭内存泄漏并修复

Closure memory leak and fix

经过 Mozilla's A re-introduction to JavaScript,以下代码导致内存泄漏:

function addHandler() {
  var el = document.getElementById('el');
  el.onclick = function() {
    el.style.backgroundColor = 'red';
  };
}

下面修改后的代码不会因为 el 没有在 onclick 函数中引用而导致内存泄漏吗?

function addHandler() {
  var el = document.getElementById('el');
  el.onclick = function() {
    this.style.backgroundColor = 'red';
  };
}

是的,内存泄漏会被阻止,你可以通过放弃局部变量 el 并直接分配元素的 onclick 属性 来更加简洁:

function addHandler(){
  document.getElementById('el').onclick = function(){
    this.style.backgroundColor = 'red';
  };
}

因此,在 onclick 回调中,this 引用执行点击事件的元素本身,因此使用 this 来设置样式很简单(即单击元素时 backgroundColor)。