views:

31

answers:

1

Hi there, 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 fields 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

+1  A: 

Hi 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

Shane Tomlinson
Do you think this is the most efficient way to get a beforeConstruction hook working?
Tom