在javascript中将定义的函数分配给对象属性

时间:2012-03-28 08:04:47

标签: 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)
};

显然错误我没有定义正在抛出......除了以下任何解决方案之外,还有什么解决方案。

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

1 个答案:

答案 0 :(得分: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();