2011-11-23 62 views
0

可能是一個非常愚蠢的問題,但我不能完全理解它:通過調用函數JS對象命名問題

我希望能夠創建一個標籤 - NEWTAB(); 我想這個函數來創建一個新的標籤對象(即我可以做的事情,如tab0.close()操作;)在獲得的對象有唯一的名稱

我的問題出現了:

//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 
    } 
} 

我知道這可能不是做事的最佳方式,所以我願意接受建議!

乾杯,

回答

3

如果你想在全球範圍內具有動態名稱聲明新的變量,使用window[tabName] = ...。否則(推薦),創建一個新對象tabs,並將所有對tabBuilder對象的引用存儲在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)); 
} 

我已經tabName = "tab" + tabQty前加入var,使變量不會泄漏到了全球範圍。另外,我添加了tabQty++,以便每個生成的名稱都是唯一的。