The function on line 14 amends an object method to intercept method calls to fire pre and post functions. The object can then continue to be used as normal.
var Calculator = function () {}
Calculator.prototype.Add = function (a, b) {
console.log("Adding a+b");
return a+b;
}
var SuperCalculator = function () {}
SuperCalculator.prototype = new Calculator();
SuperCalculator.prototype.Delete = function(a, b) {
console.log("Deleting a-b");
return a-b;
}
function createInterceptor (key, context, originalFunc, preFunc) {
var interceptor = function () {
preFunc();
var result = originalFunc.apply(context, arguments);
postFunc();
return result;
}
return interceptor;
}
var mySuperCalculator = new SuperCalculator();
var preFunc = function () { console.log("Pre func fired"); }
var postFunc = function () { console.log("Post func fired"); }
for(var key in mySuperCalculator) {
mySuperCalculator[key] = createInterceptor(key, mySuperCalculator, mySuperCalculator[key], preFunc, postFunc);
}
var addResult = mySuperCalculator.Add(1, 2);
console.log("AddResult: " + addResult);
var deleteResult = mySuperCalculator.Delete(2,1);
console.log("DeleteResult: " + deleteResult);
No comments:
Post a Comment