0

I've two different JS files in one folder. I gave a namespace to first JS file var fooMYNS = {}; and declared some variables using that namespace fooMYNS.newAr = new Array();. Now i pushed some elements in the array say {1,2,3,4}. I want to use this array details in the second JS files. How can i do it using this namespaces.

Note: Second is called/executed only after the first JS files, so array assignment is done.

Or can we do it without namespaces? Any suggestions are accepted. Thanks.

RaviTeja
  • 988
  • 3
  • 13
  • 20

2 Answers2

0

When both files are included in the page, anything declared with var outside of any object is included in the global namespace and can be accessed anywhere. You should be able to easily get to fooMYNS from anywhere on your page.

Check out this other question/answer: How do I declare a namespace in JavaScript?

However, a very nice way I've seen to explicitly declare what should be shared comes from node.js and well implemented in Coffeescript As described here: How do I define global variables in CoffeeScript?

root = exports ? this
root.foo = -> 'Hello World'

Coffeescript automatically wraps all individual files in a closure, which really helps you not pollute the global javascript namespace. As a result, it forces you to use the idiom above to ONLY expose the exact API you want.

The code above checks first for export (the node.js global), otherwise uses the closure scope (this) and explicitly attaches a method (foo) to that global space.

Now in any other file, foo will be globally accessible, but anything else not explicitly made global will not be.

Community
  • 1
  • 1
Evan
  • 7,396
  • 4
  • 32
  • 31
0

This assumes that there is at least one typo in your question - {1,2,3,4} is neither a valid array nor a valid object.

First file:

var fooMYNS = {};
fooMYNS.newAr = []; // It's faster to use an empty array than the Array constructor.
fooMYNS.newAr = [1,2,3,4]; // Not sure what happens before this that you can't just assign these values to the array in the first place.

Second file:

console.log(fooMYNS.newAr); // This outputs to the browser console [1,2,3,4]
natlee75
  • 5,097
  • 3
  • 34
  • 39