Skip to content

Instantly share code, notes, and snippets.

@zholmquist
Created October 26, 2010 22:14
Show Gist options
  • Save zholmquist/647946 to your computer and use it in GitHub Desktop.
Save zholmquist/647946 to your computer and use it in GitHub Desktop.
Function.prototype.before = function(methodName, newFunc) {
if(typeof this == "function") {
var oldFunc = this.prototype[methodName];
this.prototype[methodName] = function() {
newFunc.apply(this, arguments);
return oldFunc.apply(this, arguments);
};
} else if(typeof this == "object") {
var oldFunc = instance[methodName];
instance[methodName] = function() {
newFunc.apply(instance, arguments);
return oldFunc.apply(instance, arguments);
};
}
};
var SomeObject = function() {
this.instanceMethod = function() {
console.log("instance method");
}
};
SomeObject.prototype.someMethod = function(testParam) {
console.log("someMethod was called with: " + testParam);
return "someVal";
};
//create new SomeObject
var obj = new SomeObject();
//set before rule
SomeObject.before("someMethod", function(testParam) {
console.log("This is executed before someMethod is executed, param is: " + testParam);
});
SomeObject.before(obj, "instanceMethod", function() {
console.log("executed before instance method");
});
//call someMethod
obj.someMethod("hello");
obj.instanceMethod();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment