Skip to content

Magento 2 – Two scripts have method with same name, how to call one specific of them

Situation

The method “test” does exist two times. If I call it while both scripts are required, then only the last one is getting called e.g. the one from test2.js

app/code/Company/Test/view/frontend/web/js/test1.js

function test() { alert("test 1"); }
function foo() { alert("foo"); }

app/code/Company/Test/view/frontend/web/js/test2.js

function test() { alert("test 2"); }
function bar() { alert("bar"); }

app/code/Company/Test/view/frontend/templates/test.phtml

<script>
    require(['Company_Test/js/test1', 'Company_Test/js/test2'], function() {
        test();
        foo();
        bar();
    });
</script>

Output:

test2
foo
bar

Is there a way to only call the test method of test1.js without having to change the order of the dependencies?

I tried this:

app/code/Company/Test/view/frontend/templates/test.phtml

<script>
    require(['Company_Test/js/test1', 'Company_Test/js/test2'], function(test1, test2) {
        test1.test();
        foo();
        bar();
    });
</script>

But I get:

contacts:2964 Uncaught TypeError: Cannot read properties of undefined (reading 'test')