MOR_SNOW
MOR_SNOW

Reputation: 831

call function in external file using namespaces

Say I have 2 files, let's call them file1 and file2. Let's say file1 has a function called func1() and file2 has a function called func2()

So file1 looks something like this:

   function func1() {
      alert("func1 called");
   }

and file2 looks like this:

function func2() {
      alert("func1 called");
}

If I have loaded the file1 before the file2 in the head section of the html, I can then (in the file2) call func1 like this:

function func2() {
    func1();
}

But now... What I want to do, is to call it using a namespace. Here is where the trouble comes for me. I have read a lot about JavaScript namespacing, but the most thorough one I found is this: http://addyosmani.com/blog/essential-js-namespacing/#beginners

The problem however (like in other examples I found) is that there is too much to theory/reading (which is not a problem since it teaches a lot). By the time I have read all that, my head is so full and confused (I am new to programming, so can't handle so much yet). What I am missing from that example/link, is an explanation telling me how to make things work from 2 separate files.

So I figured I can do something like this in the file1:

var namespaceFile1 = namespaceFile1 || {};

function func1() {
    alert("func1 called");
}

What I want to be able to do now, is call the func1 using the namespace, like this:

function func2() {
  namespaceFile1.func1();
}

Trying the above solution, I get a JS error saying that namespaceFile1 does not exist, even though I declared it saying: var namespaceFile1 = namespaceFile1 || {};

How can I do this? Thanks in advance

Upvotes: 0

Views: 530

Answers (2)

anotherdev
anotherdev

Reputation: 2567

Loading 2 js files is like concatenating them. Your code should be:

var namespaceFile1 = {};

namespaceFile1.func1 = function () {
    alert("func1 called");
}

function func2() {
  namespaceFile1.func1();
}

When you speak of "namespace", it's in fact an object in which you add attributes or functions.

Upvotes: 0

Quentin
Quentin

Reputation: 944568

You've created a "namespace" (which is just a variable holding an object), but you've made the function a global instead of putting it in that namespace.

var namespaceFile1 = namespaceFile1 || {};

namespaceFile1.func1 = function func1() {
    alert("func1 called");
}

I get a JS error saying that namespaceFile1 does not exist

If it claims that, then you are trying to call namespaceFile1.func1() before you've loaded the JS file that defines namespaceFile1.

From the code you've shown, I'd expect it to say that namespaceFile1.func1 doesn't exist (i.e. "is not a function" rather than "can't access property of undefined").

You might have both errors though. Make sure you load the script that defines the function before you try to call it.

Upvotes: 2

Related Questions