2012-01-05 65 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