2016-08-14 60 views
0

刪除新添加的功能我有這種原始的功能:通過AJAX

<script> 
function f(x){..} 
function z(x){..} 
... 
</script> 

這些新功能都通過AJAX加載後:

<script> 
function xyz(){..} 
windows.abc(){..} 
... 
</script> 

如何刪除「這個」綁定的所有功能和「窗口」作用域(在這種情況下,f(x),z(x))除外。我需要這是動態的,這意味着我不知道這些新功能將會是什麼,除了它們將 綁定到「this」和「windows」範圍之外。我在考慮存儲原始函數名稱,而不是在循環中刪除它們。

+0

可以在任何的原始功能覆蓋?例如,你有一個名爲'abc'的函數,你還加載了一個名爲'abc'的函數,所以它會覆蓋第一個函數? – vlaz

+0

嗨,爲了簡單起見,它不會被覆蓋 – jfet93

回答

0

我不確定上下文是什麼,但避免用不同的值污染全局範圍。

商店當前的全球職能的數組:

// Collect existing functions into an object 
// It will look like this: { f: 1, z: 1 } 
var funcs = {}; 
Object.keys(window).filter(function (c) { 
    typeof window[c] === "function" && (funcs[c] = 1); 
}); 

// Load new stuff 
$.ajax(..., function() { 
    // After loading it, delete the functions that didn't exist before 
    Object.keys(window).forEach(function (c) { 
     typeof window[c] === "function" && !funcs[c] && delete window[c]; 
    }); 
});