Share via


Creating custom wrapper for all JavaScript functions

There might be scenarios when all JavaScript side initiated function calls need to be intercepted for logging and error reporting purposes on the client. Two approaches exist, one, calling an intermediary function and then initiating call to real function, but that could be harder to manage. Since JavaScript allows real flexibility in extending its base objects (such as String, Array, Function etc), it is quite manageable to create a custom wrapper in the base Function object and all functions will go through this route. You might decide to use this feature on as-needed basis.

In the example below, a custom wrapper known by its name is created under Function by extending the prototype property. Normal JavaScript functions (such as func and printObjects in following example) don't need to change their implementation. Only at the time of calling the real function, just replace the real function name with function name + .wrapper and pass arguments as you would normally do, starting with the "this" which is required for remembering who is the original caller of this function. e.g. a sample call could be

onclick="myFunction.wrapper(this,'x','arg2',{2,2});"

<!-- #### Code below -->
<script>
Function.prototype.wrapper = function(sender)
{
 alert("In Wrapper function first; Logging starts here");
 alert(arguments.length > 1 ? "First argument of real function is " + arguments[1] : "no additional args")
 try {
  this.apply(sender,arguments); //real function call
 }catch(exception)
 {
  //log exception on server side using XMLHTTP and/or display a generic message to user
 }
 alert("In Wrapper function; Logging ends here");
}

function func(sender)
{
 alert("Real function called");
}

function printObjects(sender)
{
 document.write("<pre>");
 for(var i in document)
  document.writeln(i + " << " + typeof(i));
}
</script>

<input onclick='func.wrapper(this,"hello",new Object());' type=button id=b value=Press NAME="b"/>
<input onclick=printObjects.wrapper(this); value=PrintObjects type=button ID="Button1" NAME="Button1"/>