for循环,元素绑定

时间:2017-10-05 18:40:18

标签: javascript loops binding

我有一个关于foor循环的问题。 为什么每次输出我的输出" 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();




我想创建一个可挂钩的中间件

2 个答案:

答案 0 :(得分:1)

以下是解决方案代码: 这样做的原因是,当您将功能分配给原始'变量它将始终引用最后一个赋值,因为原始'变量在全局范围内声明。

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();

答案 1 :(得分:0)

您只需要确保声明您的变量。 "方法"和"原创"从未宣布过。请参阅下面的工作示例:



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();