I’m trying to do a custom tabs system using JavaScript. However, in order to reuse the code I want to write it in OOP style. This what I have so far:
function Tabs()
{
this.tabArray = new Array(arguments.length);
this.tabArrayC = new Array(arguments.length);
for(i=0;i<arguments.length;i++)
{
this.tabArray[i] = arguments[i];
this.tabArrayC[i] = arguments[i]+'_content';
}
this.setClickable = setClickable;
function setClickable()
{
for(i=0;i<this.tabArray.length;i++)
{
document.getElementById(this.tabArray[i]).onclick = function()
{
alert(this.tabArray[i]);
}
}
}
}
function init()
{
tab = new Tabs('tab1','tab2','tab3','tab4');
tab.setClickable();
}
window.onload = init();
Now here’s the deal. I want to assign the onclick event handler to every tab that has been passed in Tabs ‘class’ constructor. So later in the code when I write something like:
<div id="tab1">Tab1</div>
<div id="tab2">Tab2</div>
<div id="tab3">Tab3</div>
<div id="tab4">Tab4</div>
The code which has been set up earlier:
document.getElementById(this.tabArray[i]).onclick = function()
{
alert(this.tabArray[i]);
}
… would be executed. I hope I explained that well enough. Any ideas?
There are three issues with your
setClickablefunction (edit: and an issue with how you’re callinginit):thiswill have a different meaning within the event handler you’re generating than you expect. (More here: You must rememberthis)A closure (a function that closes over data like your
ivariable) has an enduring reference to the variable, not a copy of its value. So all of the handlers will seeias of when they run, not as of when they’re created. (More here: Closures are not complicated)You’re not declaring
i, and so you’re falling prey to the Horror of Implicit Globals.Here’s one way you can address those:
…and as
goreSplatterand Felix point out, this line:…calls the
initfunction and uses its return value to assign toonload. You mean:…which just assigns
initto theonloadevent.Off-topic: You might consider using the newer “DOM2” mechanisms for attaching event handlers instead of the old “DOM0” way of using the
onXYZproperties and attributes. The new way is calledaddEventListener, although sadly Internet Explorer has only recently added that (but it hasattachEventwhich is very similar). If you use a library like jQuery, Prototype, YUI, Closure, or any of several others, they’ll smooth out those differences for you (and provide lots of other helpful stuff).