Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 470
Thomas L Holaday Avatar asked Jun 07 '09 14:06

Thomas L Holaday


People also ask

What does self mean in JavaScript?

The keyword self is used to refer to the current class itself within the scope of that class only whereas, $this is used to refer to the member variables and function for a particular instance of a class.

What does JavaScript var mean?

var is the keyword that tells JavaScript you're declaring a variable. x is the name of that variable.

Why is self needed instead of this in JavaScript?

In the JavaScript, “self” is a pattern to maintaining a reference to the original “this” keyword and also we can say that this is a technique to handle the events. Right now, “self” should not be used because modern browsers provide a “self” as global variable (window.

Is self the same as this in JavaScript?

So, within the inner function, "this" refers to the object calling the inner function while "self" refers to the object which called the outer function to create the reference to the inner function.


1 Answers

See this article on alistapart.com. (Ed: The article has been updated since originally linked)

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

Edit: Note that using self is now discouraged as window.self exists and has the potential to cause errors if you are not careful.

What you call the variable doesn't particularly matter. var that = this; is fine, but there's nothing magic about the name.

Functions declared inside a context (e.g. callbacks, closures) will have access to the variables/function declared in the same scope or above.

For example, a simple event callback:

function MyConstructor(options) {    let that = this;      this.someprop = options.someprop || 'defaultprop';      document.addEventListener('click', (event) => {      alert(that.someprop);    });  }    new MyConstructor({    someprop: "Hello World"  });
like image 197
Jonathan Fingland Avatar answered Oct 01 '22 00:10

Jonathan Fingland