Gotcha: var x = x() in Javascript gives “Object Expected” error
At ClipFlair Studio (a Silverlight app), I had some time ago implemented a confirmation warning upon user trying to close the webpage (when it was running inside the web browser), which then had stopped functioning. It seems at some refactoring I had added code like the following:
var activityView = activityView();
and it was failing with error “Object Expected” (and even worse this was done silently – had to use browser’s debugging tools to catch it – because the respective code was running at onbeforeunload browser window event).
Such code would be fine in C#, but in Javascript it seems that a local variable with name x hides a function named x (with any number of parameters in its definition). This is obviously because functions are first-class objects in Javascript and can be treated like variables themselves too.
All started working again fine after changing that code to:
var a = activityView();
Below is the respective block of Javascript code included in a script tag at the webpage that hosts the Silverlight control. Note the “control.content.activityWindow”, where “activityWindow” is accessed via the Silverlight HTMLBridge (that object – that has to be marked with ScriptableType class attribute – is registered using that key via HtmlPage.RegisterScriptableObject at the Silverlight app side).
function silverlightControl() { return document.getElementById("silverlightControl"); } function onSilverlightLoad(sender, args) { var control = silverlightControl(); if (control != null) control.focus(); } function activityWindow() { var control = silverlightControl(); if ( (control != null) && (control.content != null) ) return control.content.activityWindow; else return null; //need this so that it doesn't return undefined } function activityView() { var a = activityWindow(); if (a != null) return a.GetView(); else return null; //need this so that it doesn't return undefined } function onClosing() { var a = activityView(); if ( (a != null) && (a.WarnOnClosing) ) return "Do you want to exit ClipFlair Studio?";
//else return undefined is implied (no onClosing message that is) } function onClosed() { var a = activityView(); if (a != null) a.WarnOnClosing = false; } function installEventHandlers() { window.onbeforeunload = onClosing; window.onunload = onClosed; } installEventHandlers();