The Importance of 'this' Scope Management Through Javascript Event Handlers
During the development of vBulletin 3.x, much of our Javascript code started to take on a far more object-oriented style. With more widespread use of client-side scripting for features that would appear multiple times on a page, such as popup-menus vBMenu and collapsible elements vBCollapse , having encapsulated code made development much easier. With one exception - event handling. Let's take some very simple code to illustrate the problem. The purpose of this code is to force all links to be diverted through a different script. It's overkill, but it illustrates the problem. function linkRedirect(link_element) { this.redirect_base = "http://example.com/redirect?url="; this.link_element = link_element; this.link_element.addEventListener("click", this.handleClick, false); } linkRedirect.prototype.handleClick = function(e) { e.preventDefault(); // The following will not work window.location = this.redirect_base + escape(this.link_element.getAttribut...