i am dustin diaz

a JavaScriptr...

boosh.

don't worry about it.

Awkard Looking JavaScript

I'd like to think I have a pretty good grasp on the JavaScript langauge. And for the most part, I know how to write well-organized JavaScript and of course I know how most of the syntax looks like including control stuctures, where to insert semi-colons, comma's, curley braces, and square brackets. Plus there's the notations such as dot notation, subscript notation, both of which can make up object notation. Then there's different ways to set up functions and where you can insert parenthesis or declare anonymous functions. Oh then there's closures which are inner functions...

Ok, straight and to the point. Douglas Crockford writes about private properties and methods within the JavaScript language. Simple enough. I buy it, and, well of course, it makes sense too. There was one thing however that caught my attention. But this has nothing to do per sé with Douglas' discussion on private methods. It has to do with self-invoking functions and the similarities between how a function can be constructed.

Here is the example quoted as per Crockford:

function constructs

/* Note: The function statement */

function membername() {

  // do stuff here

}



/* is shorthand for */



var membername = function() {

  // do stuff here

};
Cool. Makes perfect sense. Now let's introduce some self-invoking behaviors to these two types of styles.

self-invoking function examples

(function i_am_anonymous(me) {

	alert(me);

}('one'));



(function i_am_anonymous() {

	alert('two');

}());



// hell, why even have a function name

(function() {

	alert('three');

}());



var so_what_am_i = function(me) {

	alert(me);

}('huzzah');

Ok now, first off all, self-invoking syntax is the wierdest looking syntax in the JavaScript language. That may be partly because I don't have CS degree. Nevermind the matter, take special note to the final example where we declare what_am_i as a function. Is it in the global space? Is it in an anonymous space? You sure as heck can't call who_am_i. Or wait, yes, you can... once. And you're running it in the act of declaring it. Hence forth, self-invoking.

What's all this mean?

Nothing really. I just thought I'd point it out. Nothing special. I can talk about the usefulness of closures. But I'll save that for later. So for now, just be enlightened with this knowledge (or confused). Ciao.

this is who i am

Hi, my name is Dustin Diaz and I'm an Engineer @ObviousCorp. Previously @Twitter, @Google, and @Yahoo, author of Strobist® Info co-author of JavaScript Design Patterns, co-creator of the Ender JavaScript Framework, a Photographer, and an amateur Mixologist. This is my website. Welcome!

On this site I write about JavaScript. You can also follow along with my open-source work on Github.

This site is optimized and works best in Microsoft Internet Explorer 6.