I'm trying to dynamically alter all objects in Javascript so that its construction can be hooked. This is what I've got now, which almost works properly:
Function.prototype.beforeConstruction = function(newFunc) {
var oldObj = this;
var newObj = function() {
newFunc.apply(this, arguments);
oldObj.apply(this, arguments);
}
newObj.prototype = oldObj.prototype;
return newObj;
};
It is used like this:
someObj = someObj.beforeConstruction(function() {
//executed before someObj is constructed
});
Now, the problem is that if the object has static field开发者_如何学编程s like this:
someObj.staticField = "example";
These will get lost when resetting the object to the one with the hook. Copying the prototype does not help with this.
Can anyone help me out here? Keep in mind that this must work without the need to modify existing objects (so that it can be used for existing libraries).
Regards, Tom
not sure if this is what you are after, but you could try looping over all the properties in the original someObj and copying their values to newObj.
Function.prototype.beforeConstruction = function(newFunc) {
var oldObj = this;
var newObj = function() {
newFunc.apply(this, arguments);
oldObj.apply(this, arguments);
}
// copy static fields here.
for(var key in this) {
// This will not copy static fields of any base classes.
if(this.hasOwnProperty(key)) {
newObj[key] = this[key];
}
}
newObj.prototype = oldObj.prototype;
return newObj;
};
MozDev has an article explaining hasOwnProperty - https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/hasOwnProperty
精彩评论