2011-04-21 189 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

相關問題