3

When I create a JS namespace (myNamespace) with a public method (myPublicMethod)

jsfile1.js

var myNamespace=(function() {

  var myPublicMethod=function(){
    alert("hello world");
  }

  return
  {
     myPublicMethod:myPublicMethod
  };

})();

and then have a separate .js file which encapsulates its methods

jsfile2.js

(function(){
  myNamespace.myPublicMethod();
})();

The two files are then included in an html file

<script src="jsfile1.js"...>
<script src="jsfile2.js" ...>

When I try to call myPublicMethod() I get an error that myNamespace does not exist. Is this because it is encapsulated in the jsfile2.js file?

Thanks

ChrisP
  • 9,796
  • 21
  • 77
  • 121
  • You missed the most crucial change... I've revised jimr's answer to point it out explicitly. – Shog9 Aug 28 '09 at 23:19

3 Answers3

7

The reason that the function isn't defined in your namespace is because of the lines

return
{
   myPublicMethod:myPublicMethod
}

An implied semicolon is inserted after the return, so what the interpreter sees is actually something like:

return;
{
   myPublicMethod:myPublicMethod
}

So nothing is actually returned from the function, and the value of myNamespace remains undefined. The fix is easy: just put the opening brace on the same line as the return:

return { 
  myPublicMethod: myPublicMethod
};

(note that the trailing semicolon is not strictly required, but a good idea anyway if you ever plan to use something like a minifier)

Also, the way you're defining the function in the first file is invalid. It should be

var myNamespace = (function() {
...
})();
Community
  • 1
  • 1
jimr
  • 11,080
  • 1
  • 33
  • 32
  • Revised according to your example, changes above, and still getting same error. – ChrisP Aug 28 '09 at 23:05
  • Moving the { to the same line as the return worked. Interesting that you have to put the opening brace on the same line as the "return". Seems inconsistent with the way some other aspects of the language work. Thanks. – ChrisP Aug 28 '09 at 23:41
1

Would changing file 1 to the following work?

var myNamespace={

  myPublicMethod: function(){
    alert("hello world");
  }
};
ferdley
  • 2,882
  • 2
  • 18
  • 7
1

You have missing parenthesis on your myNamespace function declaration, also you should use semicolons in your return statement:

var myNamespace = function () {

  var myPublicMethod = function(){
    alert("hello world");
  }

  return {
     myPublicMethod : myPublicMethod
  };
}();

myNamespace.myPublicMethod();
Shog9
  • 156,901
  • 35
  • 231
  • 235
Christian C. Salvadó
  • 807,428
  • 183
  • 922
  • 838