2012-12-23 39 views
0

我正在研究按钮程序的事情。我有一个Button对象被分配给HTML中的每个按钮。由于有不同类型的按钮,我希望有一个不同的构造函数来使对象适合每种类型。具有不同构造函数的对象

我明白我将如何去调用这些单独的构造函数,但我不知道要在构造函数中放置什么以使其将某些变量应用于Button对象。

示例按钮对象:

var Button = function(){ 
    if (buttonType == 'type1'){ 
     buttonType1(); //set onclick, onmouseover/mouseout, onmousedown/mouseup 
    } 
    else{ 
     buttonType2(); //set different ways to handle events 
    } 
} 

如何一个Button对象被创建:

var buttons = document.getElementsByClassName('button'); 

Buttons = new Buttons_Objs(); //An object to store references to all Button Objs. 

for (i = 0 ; i < buttons.length ; i++){ 
    button = buttons[i]; 
    buttonType = button.getAttribute('type'); 
    Buttons['button' + i] = new Button(button, buttonType); 
} 

我将如何构建这些函数来设置的onclick之类的东西,并且会在哪里一个存放它们的好地方,如果我不想让它们挤满我的Button对象。

+2

这闻起来像一个学校作业。无论如何,你使用的术语并不能反映你上面提供的小代码。你能提供你正在处理的所有代码,所以你的问题可以更准确地回答吗? – zero

+0

@zero这不是一个学校作业,我在下学期开始计算机科学,这只是一个个人学习项目。 向我发送我工作的测试页是否合适? – MichaelMitchell

+0

@zero我添加了一些代码,显示每个Button对象是如何制作的。 – MichaelMitchell

回答

1

所有你介绍的是一个正常的javascript函数(不是一个构造函数),你可以添加一个参数是这样的:

var Button = function(buttonType){ 
    if (buttonType == 'type1'){ 
     buttonType1(); //set onclick, onmouseover/mouseout, onmousedown/mouseup 
    } 
    else{ 
     buttonType2(); //set different ways to handle events 
    } 
} 

而且,您需要调用是这样的:

Button("type1"); 
+0

请你提供一个正确的构造函数的例子,因为我很困惑。 – MichaelMitchell

+0

哇,我太蠢了,我错过了你完全放的东西,谢谢! – MichaelMitchell

相关问题