2012-03-28 196 views
1

我有一個javascript對象和一些已定義的函數。但我怎樣才能將這些功能分配給對象屬性。我嘗試了不同的方式。但沒有希望..片段如下將定義的函數賦值給javascript中的對象屬性

// object 
var func = { 
a : '', 
b : '' 
}; 

// methods 
var test1 = function(i) { console.log(i); } 
var test2 = function(i) { console.log(i*100); } 

我需要將test1分配給a和test2給b。我試過這樣。

var func = { 
a : test1(i), 
b : test2(i) 
}; 

顯然是錯誤我沒有定義拋出..療法比低於給予其他sinppet任何解決方案。

var func = { 
a : function(i) { test1(i); }, 
b : function(i) { test2(i); } 
}; 

回答

2

這確實你問:

var test1 = function(i) { console.log(i); } 
var test2 = function(i) { console.log(i*100); } 
var func = { 
    a: test1, 
    b: test2 
} 

但不是很好的風格。

這可能會更好:

function exampleClass() {} 
exampleClass.prototype.a = function(i) { console.log(i); }; 
exampleClass.prototype.b = function(i) { console.log(i*100); }; 

var exampleObject = new exampleClass(); 
+0

是他們的任何其他適當的方式..而不是此變種FUNC = { 一:功能(I){test1的(我); }, b:function(i){test2(i); } }; – 2012-03-28 08:10:02

+0

更新了我的回答 – 2012-03-28 08:11:07

+0

謝謝..祝你有美好的一天 – 2012-03-28 08:12:14