I'm trying to hook the creation of objects in Javascript. This is easy for methods, but afaik not for constructors. I cannot change the way to create objects as this has to work for current libraries.
Anyway, this is what I have now:
Function.prototype.afterConstruction = function(hookFunc) {
var oldObj = this;
var newObj = function() {
oldObj.apply(oldObj, arguments);
hookFunc.apply(oldObj, arguments);
}
newObj.prototype = oldObj.prototype; //copy prototype fields of oldObj
for (var key in oldObj) { //copy static fields of oldObj
if (oldObj.hasOwnProperty(key)) newObj[key] = oldObj[key];
}
return newObj;
};
This is how it's used:
SomeObj = SomeObj.afterConstruction(function() {
//executed after SomeObj construction
});
The problem is that it seems to create problems with prototype methods, even though I copy the prototype.
This issue is shown in the following jsfiddle: http://www.jsfiddle.net/6rBTZ/1/
If you run it with firebug开发者_如何学Python, it'll give you a _thisInstance.onTextChange is not a function, because of the afterConstruction call earlier on this object.
Any help or improvements to my construction hooking is appreciated.
The problem is this line here:
oldObj.apply(oldObj, arguments);
In your code, you never actually create an instance of oldObj
- you're creating an instance of newObj
. Since you're technically replacing the old constructor with a new one, you need to be applying the old constructor function to your replacement's instance:
oldObj.apply(this, arguments);
http://www.jsfiddle.net/AndyE/6rBTZ/9/
精彩评论