Creating a JavaScript library

Looking to develop a JavaScript library and manage it in the following manner:

var c1 = Module.Class();
c1.init();
var c2 = Module.Class();
c2.init();

It's crucial that c1 and c2 do not share the same variables. My initial thought is to use objects:

var Module = {

     Class: {

         init: function(){
             ...
         }

     }

}

However, this structure doesn't allow for multiple instances of Class. I've been attempting to achieve the same using functions, but encountering issues:

(function() {

    var Module;
    window.Module = Module = {};

    function Class( i ) {
        //How can "this" refer to Class instead of Module?
        this.initial = i;
    }

    Class.prototype.execute = function() {
        ...
    }

    //Public
    Module.Class = Class;

})();

Unsure if this approach is feasible and open to alternate suggestions on creating this module. Not sure if it's pertinent, but I am incorporating jQuery within this library.

Answer №1

How to Use:

var c1 = Module.Class("c");
var c2 = Module.Class("a");
var n = c1.initial(); // returns 'c'
c1.initial("s");
n = c1.initial(); // now returns 's'

Module Script:

(function(window) {
    var Module = window.Module = {};
    var Class = Module.Class = function(initial)
    {
        return new Module.Class.fn.init(initial);
    };
    Class.fn = Class.prototype = {
        init: function(initial) {
            this._initial = initial;
        },
        initial: function(v){
            if (v !== undefined) {
                this._initial = v;
                return this;
            }
            return this._initial;
        }
    };
    Class.fn.init.prototype = Class.fn;
})(window || this);

This code follows the JavaScript "Module" Design Pattern, commonly used in libraries like jQuery.

If you want to learn more about the "Module" pattern, check out this helpful tutorial: JavaScript Module Pattern: In-Depth

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

Leverage variables in the path of your Express.js route

Currently in the process of developing a web application using the MEAN stack and I have a specific scenario in mind: Users should be able to sign up, but then they must also register at least one company. Upon registering a company, the base URL struct ...

JavaScript function for Removing, Saving, and Updating Quantities in the Shopping Cart

Just starting to learn how to code. I'm working on a basic Book Shopping Cart page: Shopping cart The main objective is to be able to ADD items to the cart, SAVE the cart contents, and REMOVE items from the cart whenever necessary using the template ...

What is the procedure to change a matter body's isStatic property to false in matter.js upon pressing a key?

During my recent project, I encountered a challenge in trying to set the isStatic property of a Matter Body in matter.js to false when a key is pressed. if (keyIsPressed(UP_ARROW)) { this.body.isStatic(false) } Could you provide guidance on the correct ...

Comparing the value of a variable inside a class with a global variable declared as let is not possible

I am facing an issue while trying to compare a variable named 'let hours' within my class. The comparison needs to be done in a separate function called 'utcChange' after clicking a button. I initially declared this variable at the begi ...

Canvas js displaying blank image instead of loading

I'm working on a website that includes a canvas with an image, but for some reason the image is not displaying and I can't seem to identify the issue in the code. var canvas = document.getElementById("canvas1"); var ctx = canvas.getContext("2d ...

Avoid TypeError: cannot read property '0' of undefined in a Vue.js/Django project

I am currently working on a Django/Vue.js application. Upon submitting the login form, the Django view redirects to the user's username page, where the Vue.Js file retrieves data from the server. Below is the code snippet: async created(){ await ...

Setting up a spotlight in three.js

After following the initial tutorial for three.js, I hit a roadblock when attempting to incorporate a point light into the scene. Despite numerous attempts to tweak my code, the cube remains unlit by the point light. var scene = new THREE.Scene(); var cam ...

Ignore one specific file when importing all files in Angular 7

In my Angular 7 project, I am utilizing C3 and importing all the necessary files at the beginning of my .ts component file using a wildcard. import * as c3 from 'c3'; While this method works well overall, I encountered an issue where my CSS ove ...

Ionic: setInterval/setTimer not functioning after 5 minutes in the background

In need of a timer that can send notifications via the OneSignal API after a user-defined time period is reached. Users can set the timer for any value between 1-59 minutes. Despite attempts to use the background mode plugin, specifically setInterval and s ...

Accessing the specific data I require is proving to be a challenge on Express-Gateway

Great job team! I successfully launched my Node JS project on PORT 8001 http://localhost:8001/companies_getAll (returns data) I'm planning to implement a microservice architecture using EXPRESS-GATEWAY. However, despite configuring the settings belo ...

Using a variable called "Url" instead of "window.location" in JavaScript is not functioning as expected

onclick="window.location = 'index.php'" While the above code seems to be functioning correctly, the code below is not performing as expected. Can you identify the issue? <?php $link = 'index.php'; ?> <script> var link= ...

What could be causing the DATE_SUB function to fail in executing a MySQL query through Node.js?

I am encountering an issue with a datetime field in a MySQL database table on Planetscale. My goal is to subtract some time from the datetime value using the DATE_SUB function. While this operation works smoothly in the database console on Planetscale&apos ...

Using VueLoaderPlugin() results in an 'undefined error for 'findIndex' function

Currently, I am in the process of integrating a Vue CLI app into another web project that we are actively developing. The Vue app functions without any issues when utilizing the development server bundled with Vue CLI. Due to the presence of .vue files wi ...

Framework7: Reload the current page and add it to the page history stack

I'm working on a Cordova Android app with Framework7 integration. Is it possible to stack the same page multiple times in the page history? Imagine I'm currently on the "category.html" page. I need to navigate to nested subcategories, but sinc ...

Having trouble assigning more than one custom named property in TypeScript for MUI v5 Palette

I am currently setting up multiple custom attributes to make future updates easier. Nonetheless, I'm encountering a challenge with implementing more than one custom property in MUI v5. TypeScript Error TS2717: Subsequent property declarations must hav ...

Toggling a div updates the content of a different div

I am looking to make the content within <div class="tcw-content"> dynamically change when a different div is clicked. I have little experience with Ajax, so I'm wondering if there are alternative ways to accomplish this using JS/CSS. If anyone h ...

transferring information from browser storage to the server

On my web app, there is a feature that saves data to local storage and converts it to a JSON object. I'm interested in passing this local storage data to my server using AJAX, so that other clients of the web app can access it. Is there a way to accom ...

The functionality of Change Detection is inconsistent when data is being received from the Electron Container IPC Channel

I have a program that is waiting for incoming information from an IPC Renderer Channel. Here is how I have it set up: container sending data to Angular app (mainWindow): mainWindow.loadURL('http://www.myangularapp.com') //location of the angul ...

What is the reason behind TypeScript indicating that `'string' cannot be assigned to the type 'RequestMode'`?

I'm attempting to utilize the Fetch API in TypeScript, but I keep encountering an issue The error message reads: Type 'string' is not assignable to type 'RequestMode'. Below is the code snippet causing the problem export class ...

Looking to activate a button upon clicking a button on a different page using php and javascript

Is it possible for the first user logged in on one page to have a button, and when clicked, enable a disabled button on another page where the second user is logged in? This functionality needs to be implemented using PHP/JavaScript. Thank you in advance ...