0

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?

Kristofer Gisslén
  • 1,252
  • 1
  • 11
  • 28

1 Answers1

2

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>
I wrestled a bear once.
  • 22,983
  • 19
  • 69
  • 116