What underlies this JavaScript idiom: var self = this?

I saw the following in the source for WebKit HTML 5 SQL Storage Notes Demo:

function Note() {
  var self = this;

  var note = document.createElement('div');
  note.className="note";
  note.addEventListener('mousedown', function(e) { return self.onMouseDown(e) }, false);
  note.addEventListener('click', function() { return self.onNoteClick() }, false);
  this.note = note;
  // ...
}

The author uses self in some places (the function body) and this in other places (the bodies of functions defined in the argument list of methods). What’s going on? Now that I’ve noticed it once, will I start seeing it everywhere?

10 Answers
10

Leave a Comment