Created
October 26, 2010 22:14
-
-
Save zholmquist/647946 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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