Why is a javascript function unaccessible from another script file? [duplicate]

163
January 17, 2018, at 03:33 AM

This question already has an answer here:

  • What is the scope of variables in JavaScript? 24 answers

I have a problem I've been searching SO for answers to, but nothing seem to do it for me. I've referenced a question that mimics my problem but the solution still don't solve my problem.

Accessing function in another .js file with $.getScript

My problem is as I've mentioned similar. I can't access a method inside a script file from another script file. These are my codes:

page.js

$(document).ready(function () {
    $.getScript('script.js').done(function () {
        $('#build').append(literals.test()); // $('#build') is a span tag in the HTML-file.
    }).fail(function () {
        console.warn('Unable to load script file.');
    });
});

script.js

(function ($) {
    var literals = {
            test: function () {
                return 'Hello world!';
            }
        };
})(jQuery);

This still returns the following error even though I've built it almost exactly the same way as in the answer of the referenced question.

Uncaught ReferenceError: literals is not defined at Object.<anonymous>

What am I doing wrong here?

Answer 1

Because when you create a closure, anything inside of it is only visible to other things in that scope.

In JS, all functions are closures.

(function(){
    // this is a closure
})()

If you want to be able to get the literals functions from outside of the closure, one option is to return it from the function...

const literals = (function($){ 
    return { 
        test: function () { 
            return 'Hello world!'; 
        } 
    }; 
})(jQuery); 
 
console.log(literals.test());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

READ ALSO
Dynamically settings contents of iframe and resize

Dynamically settings contents of iframe and resize

If I have the following iframe

200
Navbar sticks to top before reaching scroll point and won&#39;t return until reload of page

Navbar sticks to top before reaching scroll point and won't return until reload of page

I'm trying to implement a sticky navbar to a webpage I'm making

120
Collapse non-active Div&#39;s when hyerlink clicked

Collapse non-active Div's when hyerlink clicked

I have a web page https://websiterightco

135
vs2017 &ldquo;the process or thread has changed&rdquo; issue

vs2017 “the process or thread has changed” issue

I know this question has been asked before here: The process or thread has changed since last step and The process or thread has changed since last step (Visual Studio) as well as othersBut before yesterday it never happened to me before, The code is basically...

263