Thomas L Holaday Thomas L Holaday - 1 month ago 12
Javascript Question

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?

Answer

See this article on alistapart.com

self is being used to maintain a reference to the original this even as the context is changing. It's a technique often used in event handlers (especially in closures).