firasKoubaa firasKoubaa - 29 days ago 6
Javascript Question

Javascript : How access to a local function from global code

I have a function inside of an immediately invoked function expression and I want to be able to access that function globally without lexically scoping it that way.

How can I access this "private" function through a namespace called "App"?

indew.html:

<html>
<head>
<meta charset="utf-8">
<title>Test</title>
<script src="filtering.js"></script>

</head>
<body>
<article>
<p>
Computer graphics is widespread today. Computer imagery is found on televi
surfaces, illumination sources, and so forth, perhaps with a dynamic (time) component".[3]
</p>
</article>
<section id="result"></section>

<script>
App.showOccurenceFiltering(); // here is my wrong call
</script>
</body>
</html>


js script :

var App = (function () {
function showOccurenceFiltering() {
"use strict";
var filteredWordsArray = filtering(),
resultView = "<ol>";
for (var i = 0; i < filteredWordsArray.length; i++) {
var partWord = filteredWordsArray[i].substring(0, filteredWordsArray[i].indexOf(" ")), // de 0 jusqua l espace : la partie mot
partNumber = filteredWordsArray[i].substring(filteredWordsArray[i].indexOf(" ") + 1); // de l'espace à la fin : la partie number
resultView += "<li>" + partWord + " (" + partNumber + ")</li>";
}
resultView += "</ol>";
document.getElementById('result').innerHTML = resultView;
}
}(App));


so i got an error of a miss call like shows the capture :
enter image description here

how should i resolve my problem ??

Answer

You'll need to expose the function to the global scope. You can do this with a namespace, like this:

(function () {
   function showOccurenceFiltering() {
    "use strict";
    var filteredWordsArray = filtering(),
        resultView = "<ol>";
    for (var i = 0; i < filteredWordsArray.length; i++) {
        var partWord = filteredWordsArray[i].substring(0, filteredWordsArray[i].indexOf(" ")),  // de 0 jusqua l espace : la partie mot
            partNumber = filteredWordsArray[i].substring(filteredWordsArray[i].indexOf(" ") + 1); // de l'espace à la fin : la partie number
        resultView += "<li>" + partWord + " (" + partNumber + ")</li>";
    }
    resultView += "</ol>";
    document.getElementById('result').innerHTML = resultView;
   }

   // Prepare a "dummy" object
   var obj = {};

   // Attach the private function to this object
   obj.showOccurenceFiltering = showOccurenceFiltering;

   // Attach the dummy object to the global scope in a controlled namespace:
   window.App = obj;

}());

Then you can access the function like this:

 App.showOccurenceFiltering();
Comments