2011-04-21 220 views
0

我有一个bar类型的对象,它有一个数组foo s。javascript将对象方法传递给不同的对象方法

我想能够动态地调用foo的方法 - 我可以通过传递一个字符串来做到这一点,但我宁愿得到如何传递函数的句柄。

我是否 - 在概念上 - 正确地做到这一点?到处

bar = function() { 
    var foos = []; 

    construct = function() { 
     foos[0] = new foo(); 
    };construct(); 

    this.callFoo = function(f) { 
     return foos[0][f].apply(foos[0]); 
    }; 
}; 

回答

2

您泄漏全局:

var foo = function() { 
    this.methodA = function() { 
     return "a"; 
    }; 
    this.methodB = function() { 
     return "b"; 
    }; 
}; 

var bar = function() { 
    var foos = []; 

    this.construct = function() { 
     foos[0] = new foo(); 
    }; this.construct(); 

    this.callFoo = function(f) { 
     return foos[0].f(); 
    }; 
}; 

b = new bar(); 
b.callFoo(foo.methodA); //<-- This doesn't work 
b.callFoo(methodA); //<-- Or this 
+0

Aah以数组元素的形式访问函数。真棒。 – willoller 2011-04-21 18:40:16

+0

至于在我真正的代码中的全局变量,我使用this.callFoo(),this.construct()等 - 没有与var声明相同的结果? – willoller 2011-04-21 18:41:36

+0

@willoller你必须做'this.construct = ...'。 'construct = ...'写入全局范围。 – Raynos 2011-04-21 18:45:06

0

尝试。

// global leak 
foo = function() { 

    // global leak 
    methodA = function() { 
     return "a"; 
    }; 
    // global leak 
    methodB = function() { 
     return "b"; 
    }; 
}; 
// global leak 
bar = function() { 
    var foos = []; 
    // global leak 
    construct = function() { 
     foos[0] = new foo(); 
    };construct(); 

    this.callFoo = function(f) { 
     return foos[0].f(); 
    }; 
}; 

b = new bar(); 
b.callFoo(foo.methodA); //<-- This doesn't work 
b.callFoo(methodA); //<-- Or this 

要回答实际问题,请尝试此操作。

var foo = function() { 
    return { 
     methodA: function() { return "a"; }, 
     methodB: function() { return "b"; } 
    }; 
} 

var bar = function() { 
    var foos = []; 

    return { 
     construct: function() { 
      foos.push(foo()); 
     }, 
     callFoo = function(name) { 
      return foos[0][name](); 
     } 
    } 
} 

b = bar(); 
b.callFoo("methodA"); 
+0

这有什么用? – Raynos 2011-04-21 18:18:16

相关问题