There are various issues with your script that you're not seeing because of the way you execute it. You should select the entire code and then execute it to get a closer result to how it should work as a whole. Once you'll do that it will be easier to pick out the mistakes and fix them.
Yes, it's the currently active document (if one exists), or a generic Root object otherwise.
That's useful, and I can now see why the code partially worked.
I assume that if you run two commands, the first of which changes the active document, that in the second command "this" will be the newly active document. But is it so dynamic that this works even within a single command, or is "this" bound at the start of the command?
Is the behaviour written down anywhere by Adobe? The JS API seems silent on the matter, despite a useful discussion of "this".
Exactly, that's one of the problems with the code.
Actually, Acrobat isn't always very consistent on this issue and it's best
not to rely on the "this" object when working with multiple documents. In
such cases I prefer to maintain a variable pointing to each document that I
want to work with, since sometimes the "this" object changes during
execution, and at other times it doesn't (and no, this is not very well
For example, if you extract some pages of a document to a new file, the new
file is opened and becomes active, but is not pointed to by "this". So
running this code (as a whole script!):
Will show the path of the original file, not the newly extracted document.
But if you run the same code one line at a time, the alert will show the
path of the new temporary file created by the extractPages command...
Interesting, thanks. I suspect part of the problem is that beginners find many examples using "this" and string them together without ever really examining what "this" means.
I think I would use a simple rule:
1. Don't use "this" if there is any alternative.
2. Never, ever use "this" in a subroutine
3. If you find you have to use "this", assign it to a variable at the very start so it is used only once.
var fullDoc = this ;
var newDoc = fullDoc.extractPages ( nStart : 0 ) ;
I agree with your recommendations, although for most simple scripts there
shouldn't be a problem using it, and also in the console it's pretty safe,
unless you work with multiple documents.
Your second rule, regarding sub-routines, is a good one to remember. Also,
I would refrain from using "this" in folder-level scripts, especially those
that are executed when the app opens.
Another thing to avoid is dropping "this" at all, as it can be used
implicitly, for example: