Javascript Object constructor override to stop certain methods be called

381 Views Asked by At

A global object as such “Obj” is created:

Obj = {     
   gtm : {},
   method: function(){console.log("Method is called");}
};

In some other places Obj.method() is used.

My question is can I extend the code for “Obj” in any way to prevent the call to Obj.method(). I don’t want to rewrite or remove the codes in other places because that would be a lot of changes. Instead, I would like to change the original code so that on some condition I will just not call the method.

Proxy is not an option as Proxy will require me to change the calls in other places as well. And Proxy does not work in IE 11.

Can I rather override the constructor and achieve what I want?

Thanks and Regards

2

There are 2 best solutions below

2
Quentin On
  1. Copy the function somewhere else.
  2. Write a new function that calls it.
  3. Assign that function to the object property.

Such:

(function () {
    // IIFE for scope so we don't create another global (`method` on the next line)
    const method = Obj.method;
    const new_method = function() {
        if (your_condition) {
            method();
        }
    };
    Obj.method = new_method;
})();

If the value of this or any arguments matter, you'll need to pass them along.

e.g.

method.apply(this, arguments);
0
TKoL On

I'm not entirely sure what you're looking for, but you said

"Instead, I would like to change the original code so that con some condition I will just not call the method."

So why not do something like this:

Obj = {     
   gtm : {},
   method: function(){
      if (someCondition) return;
      // do rest of the method here
   }
};