How to pass a link to an object through functions?

I want to make:

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); } 

But of course, this overwrites what the repository is, rather than using it as a reference to a namespace property. What is the correct way to do this? I thought the [shop] window would work, but no luck.

+4
source share
2 answers

In general, it is better to avoid functions that have side effects, for example. change their arguments. If your function needs to create something, just return this "something":

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

If for some reason this does not work for you, you can also change the function argument, but the object itself must be created in the calling code:

 // worse, but possible function mkArray(xml, tag, store) { // populate store... } myStore = []; mkArray(xml, tag, myStore); 
+1
source

You can create an object and pass the object. Then change the property of the object:

 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 } 
+3
source

Source: https://habr.com/ru/post/1389435/


All Articles