What is purpose of statement like (function () { // code; }.call(this)); in JavaScript module?

131 Views Asked by At

I know using Function.prototype.call() we can write a method that can be used on different objects.

I was trying to understand source code of https://cdn.jsdelivr.net/npm/@mediapipe/control_utils/control_utils.js which is structured like this. I needed to un-minified it to see this code.

(function () {
    // code
    // code
}.call(this));

This module is getting used like


<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <script src="https://cdn.jsdelivr.net/npm/@mediapipe/camera_utils/camera_utils.js" crossorigin="anonymous"></script>
</head>

<body>
    <video class="input_video"></video>
</body>
</html>

<script>
const videoElement = document.getElementsByClassName('input_video')[0];

const camera = new Camera(videoElement, {
  onFrame: async () => {
    await someMethod({image: videoElement});
  },
  width: 320,
  height: 240
});
camera.start();
</script>

But what can be the purpose of statement like (function () { // code; }.call(this)); in JavaScript module so const camera = new Camera(arg1, arg2); camera.start(); are working?

1

There are 1 best solutions below

0
On

It is used for the export routine, which is called at the end of the script. This method is also used to keep the global scope clean of unwanted routines.

I used a beautifier, to take a better look at the minified script and it is self explaining.

[...]
    var ma = this || self;

    function K(a, b) {
        a = a.split(".");
        var c = ma;
        a[0] in c || "undefined" == typeof c.execScript || c.execScript("var " + a[0]);
        for (var d; a.length && (d = a.shift());) a.length || void 0 === b ? c[d] && c[d] !== Object.prototype[d] ? c = c[d] : c = c[d] = {} : c[d] = b
    };
[...]

This is the export function and it is only called at the end:

[...]
    K("ControlPanel", Ma);
    K("Slider", W);
    K("StaticText", Ka);
    K("Toggle", La);
    K("SourcePicker", Y);
    K("FPS", V);
    K("DropDownControl", U);
}).call(this);

It defines this["ControlPanel"] with the Ma (which is a constructor function), if it is not defined already at this.

The Function.prototype.call() can also be used for assignment on modular objects, if you execute the code inside a (Function(script).call(customObject)), then it would work like an export/import to vars.

In that case here, this should be window and only the objects named at the end will be available at the object called during creation, the function K which could be named testIfUndefinedAndSetIt won't, because it's not needed. It's just a basic routine to test if vars like ControlPanel, FPS and so on are undefined at the global scope and to prevent modifications of other scripts.