2010-10-31 78 views
0

我試圖動態地改變所有的對象在Javascript中,以便其構建可以掛鉤。這是我現在得到,幾乎正常工作:如何在Javascript正確掛鉤之前獲取類AOP對象?

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; 
}; 

它這樣使用:

someObj = someObj.beforeConstruction(function() { 
    //executed before someObj is constructed 
}); 

現在的問題是,如果對象具有這樣的靜態字段:

someObj.staticField = "example"; 

將對象重置爲鉤子時,這些將會丟失。複製原型對此沒有幫助。

任何人都可以幫助我嗎?請記住,這必須在不需要修改現有對象的情況下工作(以便它可以用於現有的庫)。

問候, 湯姆

回答

1

不知道這是你所追求的,但你可以嘗試遍歷原someObj中的所有屬性,並複製它們的值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有一篇文章,解釋hasOwnProperty - https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/hasOwnProperty

+0

你認爲這是最有效的方式來獲得beforeConstruction掛鉤的工作? – Tom 2010-10-31 22:21:17

相關問題