2009-11-02 41 views
21

我有一個功能,我不能修改:添加到一個javascript函數

function addToMe() { doStuff(); } 

我可以添加到這個功能呢? 顯然,這句法是極其錯誤的,但它的總體思路...

function addToMe() { addToMe() + doOtherStuff(); } 

回答

41

你可以存儲到原來的函數的引用,然後將其覆蓋,與回撥原來的功能,並增加了該功能,您的願望:

var originalFn = addToMe; 

addToMe = function() { 
    originalFn(); // call the original function 
    // other stuff 
}; 

你可以做到這一點,因爲JavaScript functionsfirst-class對象。

編輯:如果你的函數接收的參數,你應該使用apply將它們傳遞到原有功能

addToMe = function() { 
    originalFn.apply(this, arguments); // preserve the arguments 
    // other stuff 
}; 

你也可以使用一個自動執行的函數表達式與參數存儲原始功能的參考,我認爲它有點清潔:

addToMe = (function (originalFn) { 
    return function() { 
    originalFn.apply(originalFn, arguments); // call the original function 
    // other stuff 
    }; 
})(addToMe); // pass the reference of the original function 
+0

是的這可能是最簡單的解決方案! – mauris 2009-11-02 02:53:00

+0

完美:)太容易了。 – 2009-11-02 02:57:58

+0

謝謝:)這樣一個優雅的解決方案。 – silkcom 2012-09-05 15:30:19

相關問題