Created
June 9, 2014 20:34
-
-
Save jixunmoe/e1e882308c412e28d445 to your computer and use it in GitHub Desktop.
Hook Javascript Class Function
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
/** | |
* ClassHooker | |
* Hook original JavaScript class. | |
*/ | |
var origionalClass = function (z, y) { | |
console.group('Debug: origionalClass'); | |
console.log ('arguments:'); | |
console.log (arguments); | |
this.arg1 = z; | |
this.arg2 = y; | |
this.end = function () { | |
console.log ('== this.end called.'); | |
console.log ('this:'); | |
console.log (this); | |
console.groupEnd (); | |
}; | |
}; | |
var ClassProxy = function (that, target) { | |
for (var i=2, args=[that || {}]; i<arguments.length; i++) | |
args.push (arguments[i]); | |
var r = new (Function.prototype.bind.apply (target, args)); | |
// Modify original class. | |
r.jixun = true; | |
return r; | |
}; | |
var modifiedClass = new ClassProxy ({}, origionalClass, 123, 345); | |
modifiedClass.end (); | |
// To make this re-usable, I created this handy function. | |
// Again with original Class, but with callback this time. | |
var classHook = function (target, callback, that) { | |
// Bind init. arguments. | |
for (var i=3, args=[that || {}]; i<arguments.length; i++) | |
args.push (arguments[i]); | |
return (function () { | |
for (var i = 0, eArgs = args.slice(); i < arguments.length; i++) | |
eArgs.push (arguments[i]); | |
// When this is initialised, callback. | |
var r = new (Function.prototype.bind.apply (target, eArgs)); | |
// If nothing returned, use the original data instead. | |
return callback (r, eArgs) || r; | |
}); | |
}; | |
// Replace old class content with hooked class content. | |
origionalClass = classHook (origionalClass, function (r, eArgs) { | |
// Modify class attribute. | |
r.jixun = eArgs[3]; | |
}); | |
// `this` have independent scope and is fixed. | |
var callToOrigionalClass1 = new origionalClass (1, 2, 233); | |
var callToOrigionalClass2 = new origionalClass (1, 2, 234); | |
callToOrigionalClass2.end (); | |
callToOrigionalClass1.end (); | |
null; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment