JavaScript Late Binding?

— Barry on October 10, 2007 at 12:40 pm

This is my first nerdy post. It is about JavaScript.

Some of you stopped reading at “JavaScript” yes? Good.

Lets say I have a side bar with an edge that when clicked toggles the side bar. I want to represent this side bar as an object with the methods of show and hide. So I might have code that looks like this:

Sidebar = new function() {
    var edge = $('#sidebar_edge');
    this.show = function() {
        /* do some stuff to the UI blah blah blah I hate IE >.< */
        edge.unbind('click');
        edge.click(this.hide);
    }
    this.hide = function() {
        /* la-di-da! la-di-da! */
        edge.unbind('click');
        edge.click(this.show);
    }
}();


(The code assumes that you are using jQuery, because I am and you should.)

Now, that doesn’t work. When I bind this.hide to the click event on the last line of this.show, this.hide has not been defined. But if I change this.hide to Sidebar.hide, then it’d work just fine.

If any JavaScript gurus are reading this, please explain why that is (without telling me to read the ECMAScript specification :-P).

EDIT: Meh. I just realized that it’s probably a scope thing.

« Previous Page
This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 3.0 License. | chenb•log