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?
As mentioned several times above, 'self' is simply being used to keep a reference to 'this' prior to entering the funcition. Once in the function 'this' refers to something else.
thisss.sayHi.call(thatt);
I think the variable name 'self' should not be used this way anymore, since modern browsers provide a global variable
self
pointing to the global object of either a normal window or a WebWorker.To avoid confusion and potential conflicts, you can write
var thiz = this
orvar that = this
instead.It's a JavaScript quirk. When a function is a property of an object, more aptly called a method, this refers to the object. In the example of an event handler, the containing object is the element that triggered the event. When a standard function is invoked, this will refer to the global object. When you have nested functions as in your example, this does not relate to the context of the outer function at all. Inner functions do share scope with the containing function, so developers will use variations of
var that = this
in order to preserve the this they need in the inner function.