In C# I can write event handlers as follows:
var wdApp = new Microsoft.Office.Interop.Word.Application();
wdApp.DocumentBeforeSave += (Document doc, ref bool
The error appears to be because
In Javascript/JScript function declarations are evaluated first, before the variable is initialized. It's as if the code was written thus:
var wdApp;
function wdApp::Quit() { ... }
wdApp = new ActiveXObject('Word.Application');
The Microsoft JScript parser interprets the specially-named declaration (with ::) as an instruction to attach the function as an event handler.
But at the point of the declaration, the handler cannot be attached to the object referred to by wdApp, because wdApp at that point is still undefined. Hence, the error.
The solution is to force the function declaration to be evaluated after wdApp is initialized. This can be done in one of three ways1:
Since the function declaration is hoisted only to within the function scope, wrap the function declaration in an IIFE:
var wdApp = new ActiveXObject('Word.Application');
(function() {
function wdApp::Quit() {
//do stuff here
}
})();
Create the declaration using some sort of string -> code mechanism -- eval, setTimeout with a string, window.execScript, or new Function:
var wdApp = new ActiveXObject('Word.Application');
eval('function wdApp::Quit() { ... }`);
Initialize the variable before the current SCRIPT block. Most of the examples in the Scripting Events article do this by setting the id property on some element before the SCRIPT block:
As far as polluting the global namespace, only the third variant requires
wdAppto be in the global namespace; the other two variants can be wrapped in an IIFE.
1. Technically, there is a fourth way under IE and HTAs, but it involves non-standard HTML instead of non-standard Javascript; But it can only be used if the object is declared using the HTML
OBJECTtag, not withnew ActiveXObject( ... ).