开发者

How to get AOP-like object beforeConstruction hooks in Javascript properly?

开发者 https://www.devze.com 2023-01-23 01:43 出处:网络
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:

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

0

精彩评论

暂无评论...
验证码 换一张
取 消