A few things converged nicely for me this week: function pointers in JavaScript, and hacking the browser’s DOM. I think I’ll talk about function pointers and JavaScript’s OO, and leave browser DOM hacking for the next post.

I picked up function pointers from Ruby. They’re there in lots of languages, but Ruby’s where I discovered them. Even though I’ve been using JavaScript for years, I never saw them staring me in the face. Now that I get them, I finally get JavaScript’s OO paradigm. When you say:

1 function PublicSpeaker() {
2     this.greet = _greet;
3 }
4 function _greet() {
5     alert("Hello, everyone.");
6 }
7 new PublicSpeaker().greet();

…the deal is that this.greet is an instance variable of PublicSpeaker whose value is a function pointer, and JavaScript interprets new PublicSpeaker().greet() as “since greet is a function pointer, call the function it points to” (naturally). And when you say:

1 function BadPublicSpeaker() {
2     this.inheritFrom = PublicSpeaker;
3     this.inheritFrom();
4 }

…you’re setting the object’s instance variable inheritFrom to the
PublicSpeaker function (bummer that you have to explicitly call the super constructer, though).

[I know I can use the prototype method of establishing inheritance, but I’m not entirely comfortable with it yet…I don’t grok it, and I do grok this. And just in case, here’s what grok means.]

It seems most of JavaScript’s object-orientedness is based on function pointers. This probably explains why I hated JavaScript’s OO: I didn’t grok function pointers, so I was missing most of the picture. I could never remember that wacky syntax. I used to call it “object-scented” (oh, the hilarity).

All this improved understanding of JavaScript makes it much easier to start hacking the browser’s DOM (among other things), which I’ll get to later. In the meantime, you can dig on Object-Oriented Programming with JavaScript.