2012-01-05 76 views
4

我想做的事:如何通過函數傳遞對象的引用?

mkArray(xml, "artist", "namespace.newarray"); 

function mkArray(xml, tag, store){ 
    store = []; 
    $(xml).find(tag).each(function(i,v){ 
     store.push($(this).text()); 
    }); 
    console.log(store); 
} 

但當然,這將覆蓋店是什麼,而不是用它來命名空間的屬性的引用。什麼是正確的方式去做呢?我認爲櫥窗[商店]會起作用,但沒有任何運氣。

+2

在這種情況下,* correct *的方式,我會說,將從'mkArray'返回數組並分配它; 'namespace.newarray = mkArray(XML, 「藝術家」)' – Matt 2012-01-05 11:05:36

回答

1

一般來說,最好避免有副作用,例如功能改變他們的論點。如果你的函數應該創造一些東西,只是返回這個「東西」:

// good way 

function mkArray(xml, tag) { 
    var store = []; 
    // populate store... 
    return store; 
} 

myStore = mkArray(xml, tag); 

如果由於某種原因,這並不爲你工作,你也可以修改函數的參數,但對象本身應在調用代碼中創建:

// worse, but possible 

function mkArray(xml, tag, store) { 
    // populate store... 
} 

myStore = []; 
mkArray(xml, tag, myStore); 
3

您可以創建一個對象,並傳遞對象。然後,修改對象的屬性:

var reference = {store: void 0}; // Or just {}; 
mkArray(xml, tag, reference);  // <-- Pass the "reference" 
console.log(reference.store);  // <--- Yup. 

function mkArray(xml, tag, o_store){ 
    o_store.store = []; 
    $(xml).find(tag).each(function(i,v){ 
     store.push($(this).text()); 
    }); 
    // console.log(o_store.store); // Look ahead 
} 
+0

我只注意到了一點不同的問題。我建議看看Matts的評論。如果你想改變你的功能,而無需編輯電話的其餘部分,使用:( '')'VAR storeProps = store.split,商店=窗口;爲(VAR I = 0;我 2012-01-05 11:17:15