Guide to organizing a collection of functions within a Javascript namespace script

I'm currently working on implementing an array of functions into my script. When I utilize namespacing objects and this array, all the functions end up being labeled as undefined.

How can I construct this array in a way that ensures proper function references for processing processAllFunction?

Take a look at my code:


var myns = myns || {};
myns.test = myns.test || {};
myns.test.util = {
    myOne: function(m) {
        return m;
    },
    myTwo: function(m) {
        return m;
    },
    processAllFunction: function(m) {
        for(var i=0; i<this.replaceFilters.length; i++) {
            if(typeof(this.replaceFilters[i])==='function') {
                m= this.replaceFilters[i](m);
            }
        }
        console.log(this.replaceFilters); // undefined functions
        return m;
    },
    replaceFilters: [this.myOne, this.myTwo]
};

Answer №1

When looking at your code, the keyword this can either point to the global object window, or to the context of the function where myns is defined - hence why you are encountering an issue with undefined. To resolve this, you need a reference to the object that called the method. You can achieve this by making some adjustments:


var myns = myns || {};
myns.test = myns.test || {};
myns.test.util = {
    myOne: function(m) {
        return m;
    },
    myTwo: function(m) {
        return m;
    },
    processAllFunction: function(m) {
        for(var i = 0; i < this.getReplaceFilters().length; i++) {
            if(typeof(this.getReplaceFilters()[i]) === 'function') {
               m= this.replaceFilters[i](m);
            }
        }
        return m;
    },
    getReplaceFilters: function() {
        return [this.myOne, this.myTwo];
    }    
};

The major change is seen in the definition of getReplaceFilters where instead of directly assigning [this.myOne, this.myTwo] to replaceFilters, it is now a function that returns the array. By doing so, whenever you call

myns.test.util.getReplaceFilters()
, this will refer to myns.test.util. This same concept applies when calling
myns.test.util.processAllFunction()
; this is consistently set to myns.test.util. The value of this in these scenarios is also utilized in the invocation of getReplaceFilters within processAllFunction.

Answer №2

Here is a helpful tip: move the replaceFilters function outside of the object after declaring it.

myns.test.util = {
    myOne: function(m) {
        return m;
    },
    myTwo: function(m) {
        return m;
    },
    processAllFunction: function(m) {
        for(var i=0; i<this.replaceFilters.length; i++) {
            if(typeof(this.replaceFilters[i])==='function') {
                m = this.replaceFilters[i](m);
            }
        }
        console.log(this.replaceFilters);
        return m;
    }
};
myns.test.util.replaceFilters = [this.myOne, this.myTwo];

By using this approach, you can avoid any issues with this.

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

Should we retain the express variable for a specific purpose?

Being a developer who is still learning the ropes, I fail to understand the necessity of creating or retaining the express variable in an express/Node app. Instead of following this conventional approach: const express = require('express'); con ...

what are some advanced techniques for manipulating the DOM with a datatable?

I am currently involved in a project where we are presenting the data summary for each year to the user. The summary includes the total data for each year (counted rows). View Data Summary: Click here When the user clicks on the "+" icon, they will be ab ...

Angular unable to register service worker

Looking to implement push notifications in my Angular app using vanilla JavaScript instead of the Angular service worker or @angular/pwa. In angular.json, I've specified the path to the js file under the script option. However, when the service worke ...

What is the best way to invoke my Python function within my JavaScript file?

I am facing an issue with using my Python function in JavaScript. Although the actual code I am working on is more complex, I have simplified it to demonstrate the problem below: main.mjs dbutils.notebook.run("./aPythonFile.py", 5, {"parame ...

"Step-by-Step Guide: Integrate Cloudinary Upload Widget with Angular Framework

Struggling with integrating the Cloudinary Upload Widget into my Angular project. I followed the example code provided by Cloudinary, but it's not functioning as expected. It seems like there's a missing import or package needed to access the clo ...

Adding ObjectNodes to ArrayNodes without losing any old data can be efficiently achieved by iterating through the Array

I encountered an issue while attempting to retrieve data from the Directus API and display specific information in JSON format on my local server. My current project involves creating an API layer, which is essential for our application. Included below i ...

Sending a tailored query string through a form

Currently, when I submit a form, it directs me to the URL www.domain.com/search/?maxprice=10000000. However, I want it to redirect me to a custom URL such as www.domain.com/search/maxprice_10000000/ I came across some JavaScript code that was supposed to ...

What is the best way to utilize the same module across multiple files within a single project?

After learning that modules are cached when required, as explained in this post, I am wondering what the most efficient way is to write clean and readable code out of the various approaches available. Situation: I have three files named A, B, and C. All ...

What is the process for making a fetch request to Paypal's Oath API version 2?

After spending days working on setting up a functional payment portal on my website, I have hit a roadblock. My website does not directly sell products, but I do need to accept payments for invoices generated from my Paypal business account. To achieve thi ...

retrieving a map containing the values from an array using the `.includes()`

Currently, I am attempting to map my routes based on the roles they possess. For example, my mapped routes may have roles like ["User", "Admin"] or just ["Admin"]. The current user can have one or multiple roles assigned to them. This particular function w ...

Transfer the vector returned from a function directly into a specific location within another vector during the function call, eliminating the need for additional temporary variables [c++]

I need to optimize my function, which returns a vector, by inserting the entire vector into another vector at a specific point when calling the function. My ideal scenario would look like this: #include <vector> #include <iostream> using names ...

Obtaining data from an ajax request in node.js

My webpage has a feature that triggers an ajax request: $.ajax({ type: 'POST', url: '/usernamecheck', data: {"username":username}, success: function(taken){ ...

Converting a list of numbers into a JSON array using GSON

Currently, my code looks like this: // list is a List<Integer> JsonArray arr = new JsonArray(); for(int i : list) { array.add(i); } After reviewing the API, I am surprised that I haven't come across a more streamlined, functional way to a ...

Testing Components in Vue: A Guide to Mocking Vue Components

I have experience using React Testing Library, but I haven't used Vue Testing Library yet. I want to avoid using mount or shallowMount when testing components in VTL and figure out how to provide a stub instead. When testing a component like Componen ...

The implementation of a Like Button in Django using JS and DOM resulted in a 404 error

I am facing an issue with the 'live' like/unlike button functionality in Django and JavaScript DOM Upon clicking the button, an error is triggered POST http://127.0.0.1:8000/like/24 404 (Not Found) likePost @ javascripts.js:24 (anonymous) @ java ...

Retrieve the value from the socket client and store it in a

I have a query regarding updating socket values from another JS file. How can I achieve this? App.js io.on('connection', function (socket) { socket.currentRoomId = 0; socket.currentRoomName = "Loading..."; socket.currentRoomOwner = ...

utilizing the entire string rather than just a portion

I was attempting to create a JavaScript jQuery program that vocalizes numbers based on some previously saved data. However, I encountered an issue where only the last number in the sequence was being played (the final character in the string). Below is t ...

The setState method fails to properly update the state

I am currently utilizing React JS. Below is the code for my React class: class MyReactComponent extends React.Component{ constructor(props){ super(props); this.state = { passAccount: { email: "Email&quo ...

Allow entry fields and a submit button to become active once the form has been submitted on ASP.NET MVC 4

I want the update button to be activated after submitting the form. Take a look at my code: VIEW: @using (Html.BeginForm("ProcessTech", "Home", FormMethod.Post)) { @Html.TextBoxFor(m => m.techNo, new { @class = "form-control maintain-t ...

Convert the PHP array to JSON format and display it using the AJAX success function

Is there a way to convert the following array into JSON using PHP and retrieve it via AJAX? array(4) { ["START_TIME"]=> string(19) "2017-12-19 08:34:01" ["END_TIME"]=> string(19) "2017-12-19 10:34:07" ["DESCRIPTION"]=> string(30) ...