Saturday, August 27, 2005

 

Everything's an Object

One of the powers of JavaScript is that just about anything you work with is either an object or a property of an object. What’s more, some properties can themselves be objects too, so you end up with a hierarchy of objects. To take a simple example, consider the File System. Here, the objects are the files and folders of your file system.

By The Way: Objects vs. Object Model

But here's an irony. You can write a lot of scripts (really, useful scripts) without ever realizing that a string is an object (in the JavaScript object universe). When I first started scripting InDesign with JavaScript, I was blissfully ignorant of this. It wasn't until I discovered the Math and Date objects that it started to click with me that strings are objects too.

Once I realized this, it opened my eyes to a new world of possibilities. For example, it allowed me to create a new method for my strings that mimics the AppleScript construct is in. In AppleScript (which I used to script InDesign 1.5 and 2.0 before JavaScript became available), a very useful feature was the ability to ask if a string was in an array of strings using something like:In truth, this feature has broader applicability than for just strings albeit that 99% of the time I used it I would be dealing with strings.

Having grasped this, I created the following definition of a new method for strings in my script:
 String.prototype.isInArray = function(myArray){
  for (var i=0; myArray.length > i; i++) {
   if(myArray[i] == this){
    return true;
   }
  }
  return false;
 }
Armed with this, I could write statements like:
 If (myStyleName.isInArray(myDoc.paragraphStyles.everyItem()) {
This code snippet tests to see if the document referenced by the variable I named "myDoc" includes a paragraph style with the name contained in the variable I named "myStyleName".

It wasn't long before I realized that this method could be generalized to work with any object by simply changing the declaration to:
 Object.prototype.isInArray = function(myArray){
While it is rare that I use this method with anything other than a string, the possibility is always there.

Well, even though it's Saturday morning, I have work I must attend to, so that's it for now.

Comments:
I suspect that my AppleScript syntax isn't quite right. It's amazing how quickly details fade from memory. Scripting is definitely not like riding a bike!
 
Hi Dave,
Interestingly, you can treat anonymous strings like objects, e.g. "asdf".search("a").


Giedrius L.
 
Post a Comment

<< Home

This page is powered by Blogger. Isn't yours?