Wednesday, September 23, 2009

JavaScript Objects, Opera's Error Console

The News:

Saw Steve Forbes on CNBC yesterday. He's still spouting the supply-side nonsense that Reagan abandoned after a single-year trial. Well, his reporters are still out there reporting, and they do a good job. Wonder what Oracle is up to? Here's Ellison's game plan.

Yet another attempt to mount a frontal assault on IBM. This stupidity seems to be contagious.

JavaScript Objects

Let's create a JavaScript object.


var martin = { name: "Martin Rinehart", current_activity: "blogging" };


That's right. No class; no constructor; just create an object.

Today I've got to figure out how to do a hash in JavaScript. Let's add that:


martin.next_google = "javascript associative array";


That's right, too. Need an attribute? Assign to it. Python works this way, too. Ruby requires more Java-like planning.

Sometimes a constructor is a good thing. A regular function, first letter capitalized by convention, serves as a constructor:


function Person( name ) { this.name = name; }


Let's use that constructor to create an array of Persons.


var names = [ 'Tom', 'Dick', 'Harry' ];
var people = [];

for (name in names) { people.push( new Person(name) ); }


If you are used to Java, that probably seems more organized. You UML fans are probably breathing a sigh of relief. Forget it.


martin.kayak = 'flatwater';
people['Harry'].kayak = 'whitewater';
people['Dick'].hobby = 'gourmet chef';


Harry and I share an additional characteristic. Note that Harry is a Person; I am not. Dick, and no one else, has a hobby. (Did you notice that I did that google? JavaScript arrays are associative.) JavaScript objects are also associative arrays:


people['Tom']."rock climbs" = "Half Moon";


Actually, all the characteristic names here are strings. If you have names (no spaces or funny characters), you don't need to type the quotes. This is a convenience. Is it a good practice?

Now, is this very free-form object model conducive to good code? I don't know. JavaScript is, traditionally, bug-ridden. (Not yours, of course? I doubt it. Open the Opera browser. Click Tools/Advanced/Error Console. Now visit one of your own sites. IBM's JavaScript is a mess. Why should yours be different?)

But study that Error Console dump. Are any of the errors caused by attempts to access non-existing characteristics? I've never seen that. Your own JavaScript will get cleaned up when your developers find out that you'll be running your own sites in Opera with the Error Console turned on.

No comments:

Post a Comment