2
loader.load('scene.gltf', function(gltf){
  car = gltf.scene.children[0];
  car.scale.set(0.5,0.5,0.5);
  scene.add(gltf.scene);
  animate();
});

I found this bit of code while browsing documentation. Why and how are we passing in a complete function as a argument. Im new to JS so please guide me to the right way. :)

M -
  • 26,908
  • 11
  • 49
  • 81
bruh_moment
  • 68
  • 1
  • 4
  • 3
    A function is a value like any other JavaScript. Maybe it helps to think about functions as *callable objects*. To understand why `loader.load` accepts a function you would have to look at its implementation. It probably initializes some stuff and the function allows the caller to tell the loader that this code should be executed once the initialization is complete. – Felix Kling Jan 07 '21 at 13:38
  • 2
    Passing functions as parameters is an *extremely* common pattern in JavaScript. You might want to start with more introductory tutorials and exercises. – Pointy Jan 07 '21 at 13:39
  • It would be helpful if anyone could give a bit of documentation on this passing a function as a parameter subjec – bruh_moment Jan 07 '21 at 13:43
  • @bruh_moment not exactly the file. My best guess is that it parses the file and passes some representation of its content into the callback function. – Thomas Jan 07 '21 at 13:45
  • Here are some related questions: https://stackoverflow.com/q/483073/218196 , https://stackoverflow.com/q/6466031/218196 – Felix Kling Jan 07 '21 at 13:48
  • "It would be helpful if anyone could give a bit of documentation on this passing a function as a parameter subjec" Sry, @bruh_moment if this comes across as rude, but this is a case of "learn basics". [callbacks](https://en.wikipedia.org/wiki/Callback_(computer_programming)) are a pretty common pattern, not only in JS – Thomas Jan 07 '21 at 13:49
  • Nah don't worry it dosent sound rude. Its a mistake on my behalf to not really read up on callbacks – bruh_moment Jan 07 '21 at 13:54

1 Answers1

3

According to the three.js documentation:

.load ( url : String, onLoad : Function, onProgress : Function, onError : Function ) : null

url — the path or URL to the file. This can also be a Data URI.
onLoad — Will be called when load completes. The argument will be the loaded object.
onProgress — Will be called while load progresses. The argument will be the XMLHttpRequest instance, which contains .total and .loaded bytes.
onError — Will be called when load errors.  

Begin loading from url and call onLoad with the parsed response content. 

Thus the second argument must be of type Function, commonly called "callback", which in this particular case will be executed when the resource is finished loading.

Callback functions are a common pattern in many programming languages, JavaScript included. They serve as a way to execute code at a given time / when something is happening / has happened.

Zoli Szabó
  • 4,366
  • 1
  • 13
  • 19