bringerofrain's avatar

Acessing Functions after a compiling JS

I have a JS file and for this example, I'll make it very basic. After compiling the file through our Mix we can't access the function in the current scope.

mix.js('resources/assets/js/testfunction.js', 'public/js')

Within this file is a simple function:

function testThisFuncton() {
    alert('tested');
}

When I execute testThisFunction() in the browser client window, I get the warning the method does not exist. I can see the compiled Mix file within the new compiled testfunction public js being properly wrapped in the module.export. But not callable.

is there a variable scope I'm missing like this.Mix.testThisFunction()?

0 likes
1 reply
Krisell's avatar
Krisell
Best Answer
Level 28

Functions are not (and should not be) attached to the global scope in modern JS. If that's really what you'd like, you can just define it as window.testThisFunction = function () {}

When using mix.js, you run the JS-file through webpack and Babel, and it is put in a separate scope, basically just wrapped within an IIFE.

If you want to access the function from other files, check out ES6 modules, and if you really want to access it globally, you can attach it to the window object. However, a better option might be to create your own custom namespace, which you attach to window, and then use that for your functions/variables that you need easy access to (for instance during development).

1 like

Please or to participate in this conversation.