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?
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.
This is the export function and it is only called at the end:
It defines
this["ControlPanel"]
with theMa
(which is a constructor function), if it is not defined already atthis
.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 namedtestIfUndefinedAndSetIt
won't, because it's not needed. It's just a basic routine to test if vars likeControlPanel
,FPS
and so on are undefined at the global scope and to prevent modifications of other scripts.