0

i have a question about a foor loop. Why is my output every time "C" ?

function Dummy(){}

Dummy.prototype.a = function(){ console.log("Hello from A"); };
Dummy.prototype.b = function(){ console.log("Hello from B"); };
Dummy.prototype.c = function(){ console.log("Hello from C"); };

function hooks(obj){
 for(method in obj){
    original = obj[method];
   obj[method] = function(){
     console.log("Overrid %s", method);
      original();
    };
  }
}

var instance = new Dummy();
hooks(instance);

instance.a();
instance.b();
instance.c();

I would to create an hookable middleware

Marc
  • 2,920
  • 3
  • 14
  • 30

2 Answers2

1

You just need to make sure to declare your variables. "method" and "original" were never declared. See the working example below:

function Dummy(){}

Dummy.prototype.a = function(){ console.log("Hello from A"); };
Dummy.prototype.b = function(){ console.log("Hello from B"); };
Dummy.prototype.c = function(){ console.log("Hello from C"); };

function hooks(obj){
 for(let method in obj){
    let original = obj[method];
   obj[method] = function(){
     console.log("Overrid %s", method);
      original();
    };
  }
}

var instance = new Dummy();
hooks(instance);

instance.a();
instance.b();
instance.c();
Mack Cope
  • 31
  • 3
  • Thank you, i have forgett this in my example. My comment in the post above is what i needed. – Marc Oct 05 '17 at 18:47
1

Here is the solution code: The reason of this is that when you assign the function to 'original' variable it will always reference the last assignment because the 'original' variable is declared in global scope.

function Dummy(){}

Dummy.prototype.a = function(){ console.log("Hello from A"); };
Dummy.prototype.b = function(){ console.log("Hello from B"); };
Dummy.prototype.c = function(){ console.log("Hello from C"); };

function hooks(obj){
    for(method in obj){
        (function(original, method) {

            obj[method] = function(){
                console.log("Overrid %s", method);
                original();
            };
        })(obj[method], method)
    }
}

var instance = new Dummy();
hooks(instance);

instance.a();
instance.b();
instance.c();
Kenji Mukai
  • 599
  • 4
  • 8