Reputation: 3894
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
Upvotes: 0
Views: 106
Reputation: 31
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();
Upvotes: 1
Reputation: 599
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();
Upvotes: 1