【问题标题】:for loop, element bindingfor 循环,元素绑定
【发布时间】:2018-03-17 11:42:28
【问题描述】:

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

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

【问题讨论】:

标签: javascript loops binding


【解决方案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(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();

【讨论】:

  • 谢谢,我在我的例子中忘记了这一点。我在上面的帖子中的评论是我需要的。
【解决方案2】:

解决方案代码如下: 这样做的原因是,当您将函数分配给“原始”变量时,它将始终引用最后一个分配,因为“原始”变量是在全局范围内声明的。

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

【讨论】:

  • 虽然这可行,但@MackCope 的答案要简单得多:只需添加lets。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-05-10
  • 2021-07-23
  • 2018-03-07
  • 2016-01-26
  • 1970-01-01
相关资源
最近更新 更多