this
is the context in which the function is executed.
The trick to understanding this
is to understand that it has a function that defines it.
When you pass a function to a method like jQuery, you use that function as a callback method. jQuery explicitly sets the callback context when it is executed.
When you call an object method using dot notation: myView.render()
is a dot notation that explicitly sets the context of the method call before the object before the dot.
The rules for setting context are pretty simple in JavaScript, but can cause a lot of confusion. Most languages set a self-regulatory context variable to the object in which the method was defined. However, JavaScript uses a method invocation template to determine the context.
When we pass an object method as a callback method, the code calling it sets the context of the method - this includes baseline views and other objects. You can explicitly override this using the Underscore.js bind
and bindAll
( http://documentcloud.github.com/underscore/#bind ), as well as several other tricks.
Backbone.View.extend({ initialize: function(){ _.bindAll(this); } });
This code, for example, will bind the context of all functions of the current view object to the view. This ensures that the context of your view methods will always be the view itself.
For more details see:
source share