1

Following is my javaScript code.

var myObjfn = {
    before : function(){
        console.log("before");
    },
    loadA: function(){
        console.log("loadA");
    },
    loadB: function(){
        console.log("loadB");
    },
    loadC: function(){
        console.log("loadC");
    }
 }

Whenever I call myObjfn.loadA(), it should call myObjfn.before() method before executing loadA method. Same for loadB() & loadC(). I don't want to explicitly call before() method in all loadA,loadB and loadC methods. Is there any option to achive this in javascript ?

0

1 Answer 1

3

You could do something like this. Which creates a wrapper function for each function in the object except the before function.

var myObjfn = { ... };

Object.keys(myObjfn).forEach(key => {
  if (key === "before") return;
  var oldFunc = myObjfn[key];

  myObjfn[key] = function() {
    myObjfn.before();
    return oldFunc.apply(this, arguments);
  };
});

myObjfn.loadA();

// "before"
// "loadA"
8
  • Getting following exception Object.keys(...).each is not a function
    – Prasath
    Commented Mar 6, 2017 at 12:22
  • I checked with updated answer, same exception. I think it is minor one. I can fix it. I understood your answer which is posted. By the way if you have any idea about '.each is not a function' ?
    – Prasath
    Commented Mar 6, 2017 at 12:25
  • Yeah, I fixed that, it's .forEach instead of .each.
    – Icid
    Commented Mar 6, 2017 at 12:26
  • Before that I noticed only oldFunc = myObjfn[key]; Now working fine
    – Prasath
    Commented Mar 6, 2017 at 12:27
  • @lcid The actual thing is working. Is there any other optimal way comes in your mind?
    – Prasath
    Commented Mar 6, 2017 at 12:32

Not the answer you're looking for? Browse other questions tagged or ask your own question.