Variations in the module pattern in JavaScript

Can someone help me understand the differences in these methods of creating a javascript "module"? I'm just looking for some clarification.

A)

var foo = function() {
    var bar = function() {
        console.log('test');
    };

    return {
        bar: bar
    };
};

B)

var foo = function() {
    function bar() {
        console.log('test');
    };

    return {
        bar: bar
    };
};

C)

var foo = function() {
    this.bar = function() {
        console.log('test');
    };

    return {    
        bar: this.bar
    };
};

Answer №1

Although A and B may seem identical, there exists a subtle difference between the two due to function/variable hoisting. In theory, it is possible to write code that works in B but fails in A; however, in practical terms, one would need to purposefully craft unconventional code to achieve this outcome.

C, while functional, deviates conceptually from best practices. The use of this.funcName within a function typically suggests constructor usage for creating numerous objects with new Thing(). If the intention is not to construct objects, using this style could mislead others into thinking otherwise, mistaking the function as a constructor instead of its true purpose as a module.

Answer №2

Initially, you overlooked executing the function expression: the module pattern is an IEFE. You simply create a function.

The final example appears illogical, resembling a constructor function when assigning properties to this - and when executed as an IEFE it malfunctions (and using it with new produces unwanted effects; and returning an object renders it pointless).

To understand the distinction between the first and second code snippets, refer to var functionName = function() {} vs function functionName() {}. In the context of the module pattern, it is advisable to use function declaration.

Answer №3

//JavaScript Design Pattern
var company = (function() {
  var cname = 'CheapFlight';
  return {
   name: "Santosh Thakur",
   getAge: function() {
    return cname;
   },
   growOlder: function() {
    return cname + " Updated";
 }
 };
}());
company.cname = "New Business"
console.log(company.cname);
console.log(company.name);
console.log(company.getAge());
console.log(company.growOlder());

Answer №4

Using the prefix 'var' before a function transforms it into something akin to a class, allowing for the creation of multiple versions. This concept applies to A.

For instance:

  var hi = function()
  {
    var bye = function()
    {
        alert("bye");
    }   
    bye(); // calling bye
    var something = new bye(); // creating a new instance of bye();
  }

  var something = new hi();
  something();

In B's case, you can only invoke bar, without generating a new instance within the function itself.

C behaves similarly to bar due to its scope.

Class-like behavior:

var Dog = function( hair, type )
{
     this.hair = hair;
     this.type = type;
}

var fred = new Dog( "long", "Dalmation" );
alert( fred.hair );    

var dave = new Dog( "short", "Poodle" );
alert( dave.type);

This represents a class ^

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

Tips on how to render a component only after receiving an AJAX response

I'm encountering an issue with one of my React components. It seems like AJAX is not fetching all the content from the external server before React renders the ChildComp component. https://i.stack.imgur.com/o0ZtH.png Above, you can view the tree of ...

chart.js version 3 does not display the correct date data on the time axis

Struggling to make chart.js work with a time axis is proving to be quite challenging for me. The code I have is as follows: <html> <head> <script src="https://cdn.jsdelivr.net/npm/moment"></script> <script src="https://cdnjs.clo ...

Obtain identical encryption results with CryptoJS (JavaScript) and OpenSSL (PHP)

I am in the process of integrating a PHP encryption function into a ReactJS application. I have a requirement to transmit the token in a specific format that was generated using the OpenSSL library function (openssl_encrypt). It has been observed that the ...

Is it possible to send an email with an attachment that was generated as a blob within the browser?

Is there a way to attach a file created in the browser as a blob to an email, similar to embedding its direct path in the url for a local file? The file is generated as part of some javascript code that I am running. Thank you in advance! ...

webgl renderer for cytoscape.js

I have been exploring different layout extensions and have examined various examples from existing extensions like arbor, cola, cose-bilkent, as well as the scaffolding provided here. However, I am facing a roadblock when it comes to integrating a webGL re ...

Javascript: triggering a self-executing function manually

I have a code snippet similar to the following: var msg="first call"; (function test(msg) { console.log("inside self call"); } )(); msg="second call"; console.log("before inline call"); test(msg); console.log("after inline call"); In thi ...

Making a Jquery Ajax Request in Real Time

Is there a way to make sure that the "Test Data" text is only displayed in the console after the book details are fully loaded into vm.books? I am trying to make a synchronous ajax call for this purpose. The code below is not producing the expected result ...

Issues with aligning center vertically and horizontally using flexbox are causing unexpected behavior

Understanding the basic concepts of centering a flex container using justify-content:center and align-items: center, I am facing an alignment issue with my box. Can anyone help me with this? This is what I have attempted so far: <template> <di ...

The jQuery click event does not fire within a bootstrap carousel

I am trying to set up a bootstrap carousel where clicking on an image inside it will trigger a self-made lightbox. However, I am facing some issues with the JavaScript code not being triggered with the following syntax: $('html').on("click", ".l ...

Merge arrays to form nested structures

Here's a mind-bending scenario for you. Imagine I have two arrays - one containing categories and the other containing arrays that follow the structure of those categories. For example: var categoryArray = ["Name", "Title", "Hire Date"]; var infoArr ...

Positioning tooltip arrows in Highcharts

I'm attempting to modify the Highcharts tooltip for a stacked column chart in order to have the arrow on the tooltip point to the center of the bar. I understand that I can utilize the positioner callback to adjust the tooltip's position, but it ...

"Revolutionary AJAX-enabled PHP social commenting system with multi-form support

Why is it that when I submit forms using these ajax functions in PHP, they only send to the first form on the page? I have multiple forms under each article and I want them to be submitted separately. What am I doing wrong? ...

WordPress Media Library - Issue with select function not properly updating row index when updating ID

I am currently working on a WordPress blog that includes a custom metabox on the edit page for each post. This metabox contains a table where each row displays an image source selected from the media library. When a new row is added, it is assigned an I ...

JavaScript module declarations in TypeScript

Recently, I delved into the world of a Node library known as bpmn-js (npmjs.com). This library is coded in JavaScript and I wanted to incorporate typings, which led me to explore d.ts files. My folder structure looks like this webapp @types bpmn ...

What is the best way to run a series of basic commands in Node.js in sequence

Is there a way to execute 4 bash commands sequentially in nodejs? set +o history sed -i 's/&& !this.peekStartsWith('\/\/')/ /g' dist/vendor.bundle.js sed -i 's/&& !this.peekStartsWith('\/\/ ...

Troubleshooting problem with Ajax responseText

Can an ajax responseText be received without replacing the existing content? For instance: <div id="content"> <p>Original content</p> </div> Typically, after running an ajax request with a responseText that targets id="conten ...

The `background-size` property in jQuery is not functioning as expected

I am facing the following issue: When I click on a div with absolute positioning, I want to animate its position, width, and height. In addition, I want to change the background-size using jQuery. However, the problem is that all CSS properties are updat ...

Numerous events have been successfully integrated into the angularjs-bootstrap-calendar

Currently, I am facing a challenge with loading all my event data from the server using angular-bootstrap-calendar. Due to the large volume of events, it is taking a considerable amount of time to load. I am exploring the possibility of fetching only a mo ...

HTML checkbox utilizing JavaScript

<input type="checkbox" name="smoker"> Is there a way for JavaScript to determine whether the checkbox is checked or unchecked without making changes to the HTML code above? ...

Please be patient until setInterval() completes its task

In order to add a dice-rolling effect to my Javascript code, I am considering using the setInterval() method. To test this out, I have come up with the following code: function rollDice() { var i = Math.floor((Math.random() * 25) + 5); var j = i; ...