Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Hook Javascript Class Function
/**
* 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
You can’t perform that action at this time.