How to call a public function in Javascript namesapce

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 that encapsulates its methods

jsfile2.js

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

Two files are then included in the 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 it because it is encapsulated in the jsfile2.js file?

thanks

+3
source share
3 answers

The reason the function is not defined in your namespace is due to the strings

return
{
   myPublicMethod:myPublicMethod
}

After the return, a semicolon is inserted, so what the interpreter sees, actually looks something like this:

return;
{
   myPublicMethod:myPublicMethod
}

, , myNamespace undefined. : , return:

return { 
  myPublicMethod: myPublicMethod
};

( , , , - - minifier)

.

var myNamespace = (function() {
...
})();
+7

1 ?

var myNamespace={

  myPublicMethod: function(){
    alert("hello world");
  }
};
+1

myNamespace, return:

var myNamespace = function () {

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

  return {
     myPublicMethod : myPublicMethod
  };
}();

myNamespace.myPublicMethod();
+1

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


All Articles