0

Probably a really silly question, but I can't fathom it:

I want to be able to create a tab by calling a function - newTab(); I want this function to create a new tab object (that I can manipulate by doing things such as tab0.close();)

My problem arises in getting the object to have a unique name:

//This will be used for the object ID
var tabQty = 0;

//Call to create a tab
newTab();

//Function to make the tab
function newTab(){
   //This is how I want to make the names - tab0, tab1, tab2 etc
   tabName = "tab" + tabQty;

   // - this is my problem line - I can't use tabName = as it just overwrites the value of tabName. How do I get around this?
   return tabName = new tabBuilder(tabName);
}




function tabBuilder(tabName){
   return{
      name: tabName,
      close: function(){//blah}

      //More to come here
   }
}

I understand this may not be the best way of doing things either, so I'm open to suggestions!

Cheers,

1 Answer 1

3

If you want to globally declare the new variable with a dynamic name, use window[tabName] = .... Otherwise (recommended), create a new object,tabs, and store all references to the tabBuilder object at tabs.

var tabs = {};
function newTab(){
   //This is how I want to make the names - tab0, tab1, tab2 etc
   var tabName = "tab" + tabQty;
   tabQty++;    // Added to implement the "unique tab name" feature

   return (tabs[tabName] = new tabBuilder(tabName));
}

I have added var before tabName = "tab" + tabQty, so that the variable does not leak to the global scope. Also, I have added tabQty++ so that each generated name is unique.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.