2012-03-28 198 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