What is the reasoning behind using the IIFE pattern on certain straightforward member functions in three.js?

Consider the Object3D base class:

rotateOnAxis: function () {

    // rotate object on axis in object space
    // axis is assumed to be normalized

    var q1 = new Quaternion();

    return function rotateOnAxis( axis, angle ) {

        q1.setFromAxisAngle( axis, angle );

        this.quaternion.multiply( q1 );

        return this;

    };

}(),

... This type of pattern is commonly found in other classes as well. Instead of using a nested function within a function expression like shown above, why not just write a normal function like: function rotateOnAxis(axis, angle) {...}?

Answer №1

Utilizing a closure in this scenario prevents the need to create a new quaternion with each function call.

This particular coding technique is commonly employed in three.js, particularly within functions that are frequently called in fast-paced loops, like an animation sequence.

Version r.89 of three.js is being used.

Answer №2

After studying How do JavaScript closures work? and conducting experiments with variables in the Chrome console, I have come to the conclusion that "a closure is a stack frame which is allocated when a function starts its execution, and not freed after the function returns (as if a 'stack frame' were allocated on the heap rather than the stack!)" is a perfect way to explain this concept.

When I run 'app._scene.scene.children[0].rotateOnAxis' in the console, it displays:

ƒ rotateOnAxis( axis, angle ) {

      q1.setFromAxisAngle( axis, angle ); <-- q1 is referenced but no declaration

      this.quaternion.multiply( q1 );

      return this;

  }

Running 'app._scene.scene.children[0].rotateOnAxis.q1' results in:

undefined.

Lastly, evaluating 'app._scene.scene.children[0].rotateOnAxis.prototype' gives us:

{constructor: ƒ}  
 + constructor:ƒ rotateOnAxis( axis, angle )
 | ... (ignored here)
 | [[Scopes]]:Scopes[3]
 ---+ 0:Closure {type: "closure", name: "", object: {…}}
    |--+ q1:Quaternion {_x: 0, _y: 0, _z: 0, _w: 1} <-- scope search here
    | 1:Closure {type: "closure", name: "", object: {…}}
    | 2:Global {type: "global", name: "", object: Window}

It is evident from the above that there is a 3-layer stacking closure frame attached to the rotateOnAxis function's prototype.constructor property. It is also important to note that the variable (q1) saved in the closure will change whenever the outer function is invoked, necessitating a reset in its content within the setFromAxisAngle interface.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Automatically scroll the page upon loading if the user is at the top of the page

Is there a way to trigger an action only when the page is detected to be at the very top, without executing it otherwise? I think maybe using an if statement could work, but I'm not entirely sure how to go about it. For instance, I'd like the pa ...

Looking to switch up the hide/show toggle animation?

Currently, I have a functioning element with the following code. It involves an object named #obj1 that remains hidden upon page load but becomes visible when #obj2 is clicked. #obj1{ position:fixed; width:100px; bottom:180px; right:10 ...

Obtain image data and use it to generate particle textures in three.js

I am attempting to use the getimagedata() method on various positions within the same canvas element in order to create individual textures for particles in a particle system. I want each particle to have a unique texture that corresponds to a specific c ...

Adjust the div's height to 0

I need to dynamically set the height of a div element with a height of 34px to 0px. However, this div does not have a specific class or ID, so I can't use traditional DOM manipulation methods like .getElementById(), .getElementByClassName, or .getElem ...

Maintaining the active state in Bootstrap, even when manually entering a URL, is essential for smooth

Check out this fully functional plnkr example: http://plnkr.co/edit/p45udWaLov388ZB23DEA?p=preview This example includes a navigation with 2 links (routing to 2 ui-router states), and a jQuery method that ensures the active class remains on the active lin ...

Add new data to an existing array in Angular 7 without overwriting it

After clicking a button, I'm retrieving data from the WordPress API: <a (click)="initGetComments()">Get comments</a> This is the code snippet: export class AppComponent { commentsResults: CommentsItem[] = []; ...

Surprising outcome of Vue

As a newcomer to vue.js, I am struggling with a side effect issue in a computed property. The unexpected side effect error is popping up when running the code below, and ESlint is pointing it out in the console. I understand the concept of side effects, bu ...

The image is loaded correctly through the image picker, however, it is not displaying on the screen

When I click the button to pick an image from the gallery in this code, it is supposed to load the phone's gallery and display the selected image in the image component. Even though the image gets loaded properly (confirmed through test logs), it does ...

Strip the pound symbol from the end of a URL during an AJAX request

When I click on the News tab in my Rails application (version 2.3.4 and Ruby 1.8.7), an Ajax call is triggered to load data. <a href="News" onclick="load_feed();"><u>Show More...</u></a> <script> function load_feed() { $.a ...

What is the procedure for configuring custom request headers in Video.js?

Encountering this issue, I created a simple example using guidance from this documentation: <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <link href="https://vjs.zencdn.net/7.4.1/video-js.css" re ...

Analyzing the current time against a user-inputted time using Javascript

Looking at this html and javascript code, the goal is to compare an input time with the current time. If the input time is less than 2 hours, "Less time" should be displayed in the label; if it's more than 2 hours, then "sufficient time" should appear ...

Having trouble selecting a radio button in React JS because it's marked as read-only due to the check attribute

In my scenario, I have a child component with radio buttons. The questions and radio buttons are populated based on the data, with each set consisting of one "yes" and one "no" option. I am attempting to automatically check all radio buttons that have a v ...

Tips for managing the second datepicker for the return journey on Abhibus using Selenium webdriver

I am currently working on a code to choose departure date and return journey date, but I am encountering an issue where the return journey date is not being selected. The driver seems to be skipping over the return date selection and proceeding directly to ...

jQuery Datatables causing hyperlinks to malfunction on webpage

After implementing jQuery datatables on this example using a PHP serverside processing file pulling data from MySQL, the Sign-in button used to work but now it just reloads the same index page. Manually typing in the address linked to the Sign In page work ...

Troubiling Responsive Menu in React

I am currently working on developing a React Responsive Navigation with SCSS, but I am facing an issue. When I click on the hamburger button, nothing happens and the menu does not slide down in the mobile view. I tried inspecting the code in the browser to ...

Utilize the active tabpanel MUI component with Next.js router integration

Trying to implement active tab functionality using router pid This is how it's done: function dashboard({ tabId }) { const classes = useStyles(); const [value, setValue] = React.useState(""); useEffect(() => { con ...

My node.js code is not producing the expected result. Can anyone point out where I may be going wrong?

I've been working on a BMI calculator where I input two numbers, they get calculated on my server, and then the answer is displayed. However, I'm having trouble receiving the output. When I click submit, instead of getting the answer, I see a lis ...

Step-by-step guide for serving static JavaScript files using NextJS

I am currently exploring the process of hosting static js and css files using NextJS. My journey began with creating a react app through create-react-app, where I developed an App component before executing the npm run build command. This resulted in the ...

AngularJS: Sending form data to an external server results in an error due to restricted URI access

I am currently diving into the world of AngularJs and putting effort into mastering it. In this process, I've created a demo application that attempts to send form data to a localhost site. The code for this endeavor is provided below. index.html &l ...

Guide to Changing the Value of a Textbox Using Form jQuery

For instance: <form id="example1"> <input type="text" name="example_input"> </form> <form id="example2"> <input type="text" name="example_input"> </form> In the code above, both text boxes have the same name. H ...