tags:

views:

376

answers:

4

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?

+14  A: 

see: http://www.alistapart.com/articles/getoutbindingsituations

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).

Jonathan Fingland
Thanks for the pointer to an excellent article.
Thomas L Holaday
+2  A: 

The variable is captured by the inline functions defined in the method. this in the function will refer to another object. This way, you can make the function hold a reference to the this in the outer scope.

Mehrdad Afshari
+4  A: 

Yes, you'll see it everywhere. It's often "that=this;".

See how "self" is used inside functions called by events? Those would have their own context, so self is used to hold the "this" that came into Note().

The reason "self" is still available to the functions, even though they can only execute after the Note() function has finished executing, is that inner functions get the context of the outer function due to "closure."

Nosredna
A: 

Well, at least it's not a variable called "Me"

Rodrigo
What's wrong using "me" in place of "self"?
Marco Demajo