简体   繁体   中英

isPrototypeOf in indesign

Hi am relativly new to indesign scripting and would like to figure out if an object is a subtype of a class. Example: I want to iterate over all page items and take everything that is not a graphic:

layer = app.activeDocument.layers[layerIndex];

for (i = 0; i < layer.allPageItems.length; i++) {
  alert(layer.allPageItems[i].reflect.name)
  if(layer.allPageItems[i].isPrototypeOf (Graphic) ) {
    alert("Graphic");
  } else {
    ....
  }
}

howver the if nver matches. Are there any examples of how to use isPrototypeOf ? What do I have to do to test if an object is of a certain type or a subclass of it?

edit : To clarify, I am trying to test if I have an Instance of anything that inherited from Graphic.

But as far as I can see now that seems to be impossible.

You probably want the instanceof operator.

if (layer.allPageItems[i] instanceof Graphic) {
    alert("Graphic");
} else {
    ....
}

You could also use isPrototypeOf but you have to reverse the order and get the prototype itself, not the constructor. So it would look like this:

if (Graphic.prototype.isPrototypeOf(layer.allPageItems[i])) {
    alert("Graphic");
} else {
    ....
}

You can get access to the essence of the pageItem by calling the getElements() method. It returns an array of the original material. Given a rectangle on a page (nothing else) :

app.activeDocument.allPageItems[0].getElements()[0] instanceof Rectangle //true;

Are you sure its not supposed to be

Graphic.isPrototypeOf(layer.allPageItems[i])

or something like

Graphic.prototype.isPrototypeOf(layer.allPageItems[i])

?

Your current version sounds like its backwards.

Apparently this is not possible, I also asked on the adobe Forums with this result: http://forums.adobe.com/message/4461211#4461211

So the short answer is, I have no way to check if I hold an object wich is an instace of someClass or a child thereof. Neither reflection nor isPrototypeOf help.

I might try casting in a try catch block but consider this as ugly. Thus I will go with the solution suggested on the adobe Forums, test for all possible heirs (children/classes inherting from base) and the base class. This is ugly and lengthy but I have not found a better solution.

edit : here is an exceprt from one of adobes examples, it allows for the switch syntax avoidng an endless if construct:

switch (app.selection[myCounter].constructor.name){
    case "Rectangle":
    case "Oval":
    case "Polygon":
    case "GraphicLine":
    case "TextFrame":
        myObjectList.push(app.selection[myCounter]);
        break;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM