jfet93 jfet93 - 1 year ago 50
Javascript Question

Delete newly added functions via AJAX

I have this original function :

function f(x){..}
function z(x){..}

These new functions are loaded later via AJAX :

function xyz(){..}

How do I delete ALL functions binded in the "this" and "windows" scope except the original ones ( in this case f(x), z(x) ). I need this to be dynamic meaning I have no idea what the new functions will be except that they will be binded
to the "this" and "windows" scope. I'm thinking storing the original function names and not delete those during a loop.

Answer Source

I'm not sure what the context is, but avoid polluting the global scope with different values.

Store an array of your current global functions:

// 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];