Sunday, July 10, 2011

Javascript: The Indecipherable Sentences

From Crockford's "Javascript: The Good Parts".

"When a function object is created, the Function constructor that produces the function object runs some code like this:

this.prototype={constructor:this};

The new function object is given a prototype property whose value is an object containing a constructor property whose value is the new function object."

Say what? This is an example of completely ridiculous technical writing. What makes it even more egregiously bad is throughout his book Javascript: The Good Parts, Crockford uses railroad diagrams to illustrate Javascript's grammar. Yet the above quoted sentence, which might best be expressed via a diagram, is rendered in nearly impenetrable prose.

Joanne Programmer is writing her first useful Javascript program. When the program is run it will print the words "Jello, Whirled." She decides she will try to use a function to print the message and writes: function jelloWhirled(){ console.log("Jello Whirled!"); } She runs the program, and it works!! She is very excited. When the thrill wears off, a few seconds later, she wonders, how did the Wizard of JS do that?

The Wizard, it turns out, has some code of his own. It is not visible to Joanne, as it is embedded in the interpreter, but when Joanne writes function () {} the Wizard's code creates a function object for Joanne.

This function object the Wizard creates for Joanne has some properties. One is a prototype property. The prototype property will allow Joanne to add properties and methods to her function. If that's confusing, check out this excellent example

What is the value of the prototype property in Joanne's function? After all, properties usually have a value. According to Crockford, the value is basically a piece of code that can be used by Joanne's function to invoke itself (I think). Does the reader need to know more? Possibly, it's hard to tell from what Crockford writes.

No comments: