Skip to main content
John Hawkinson
Inspiring
March 17, 2010
Question

toString() overrides in constructor-less classes? [CS3,JS]

  • March 17, 2010
  • 1 reply
  • 3807 views

How do I override the toString() method in a class that lacks its own constructor?

(I'm actually working with the ManagedArticle class from Woodwing's SmartConnection plugin, but the probem appears to be general for any such class, so here we are with Page).

Example:

Page.prototype.toString = function() {
     return "[object Page "+this.name+"]";
     }

p0 = app.activeDocument.pages[0];
$.writeln("1: "+p0);
$.writeln("2: "+p0.toString());
$.writeln("3: "+Page.prototype.toString.call(p0));

p1 = app.activeDocument.pages.add();
$.writeln("4: "+p1);
$.writeln("5: "+p1.toString());
$.writeln("6: "+Page.prototype.toString.call(p1));

produces:

1: [object Page]
2: [object Page]
3: [object Page 1]

4: [object Page]
5: [object Page]
6: [object Page 2]

Is this a fool's errand? I'd really like easier debugging of this class and overriding the toString() would seem to be the way-to-go.

Thanks!

This topic has been closed for replies.

1 reply

Harbs.
Legend
March 17, 2010

Can I ask why you would want to override a built in method?

It sounds like a silly thing to do in JavaScript...

Harbs

Bob Stucky
Adobe Employee
Adobe Employee
March 17, 2010

I add functions to prototypes all the time (File and Folder especially). I don't typically override, though.

Meanwhile, you can do stuff like that to the standard Extendscript objects - such as File, you can't do it for InDesign DOM objects.

Bob

Harbs.
Legend
March 17, 2010

You actually can do it to InDesign DOM objects (well some of them -- in certain ways anyhow). Here's a particularly interesting one:

var itemByLabel = function (label){

    var labelIndex = null;

    var labelArray = this.everyItem().label;

    for(var i=0;i<labelArray.length;i++){

        if(labelArray==label){labelIndex = i;break}

    }

    if(labelIndex===null){return null}

    return this.item(labelIndex);

}

app.documents[0].pageItems;//needed to initialize the PageItems object

PageItems.prototype.itemByLabel = itemByLabel;

app.documents[0].paragraphStyles;//needed to initialize the ParagraphStyles object

ParagraphStyles.prototype.itemByLabel = itemByLabel;

etc...

I am very wary of prototyping anything but the simplest JS objects though...

You can do it with a regular function or method in a custom library (like Bob likes to do).

function CustomToString(object){

     var string = object.toString();

     string+="bla bla bla";

     return string;

}

Harbs