Creating an object with a unique string identifier in JavaScript

In the client, I have declared a namespace and various classes within different namespaces. The challenge arises when I receive a string from the server upon page load containing "dotted" namespace.class names, and I need to obtain an instance of one of these classes.

Currently, my approach involves using eval for this purpose. However, I have noticed that it leads to memory leaks. Hence, I am exploring alternative methods to instantiate a declared object based solely on its name. Simply attempting something like

var obj = "myNamespace.myObjectName"();
does not yield the desired result.

If I have an object name stored as a string variable, I can utilize the eval() function to generate an instance of that object:

window["myNamespace"] = {};
myNamespace.myObjectName = function() { /* blah */ };

var name = "myNamespace.myObjectName";
var obj = eval("new "  + name + "()");

However, due to various reasons, I prefer not to use eval. Is there a way to create an object by its name without resorting to eval?

Answer №1

It seems like the name variable's content is out of your control, meaning you're stuck with the inclusion of the . in the string.

One way to handle this situation is by using .split() to break down the string into its individual parts and then utilizing .reduce() to navigate through the base object.

window["myNamespace"] = {};
myNamespace.myObjectName = function() {
  this.foo = "bar"
};

var name = "myNamespace.myObjectName";
var obj = newObjectFromStringPath(name);


document.querySelector("pre").textContent = JSON.stringify(obj, null, 4);


function newObjectFromStringPath(path, base) {
  return new (name.split(".").reduce(function(obj, name) {
    return obj != null ? obj[name] : null
}, base || window))
}
<pre></pre>

The implementation of newObjectFromStringPath is tailored to target a function specifically and invoke it as a constructor. To adapt it for fetching any value, you can simply eliminate the new keyword within that function.

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

Adjusting map boundaries to match the raster layer dimensions

I have been searching through numerous tutorials on using `fitbounds` with Mapbox, but I am still unable to understand how to center my map on a specific raster layer. I have a menu that switches between various older maps and I want the map to adjust acco ...

Sending Live Data from Frontend JavaScript to Django/Python Backend

Despite my efforts to find a solution on various platforms and websites, I have not been able to locate an answer that addresses my specific query. The issue at hand involves a webpage with buttons marked "+" and "-", which are intended to adjust a variabl ...

Exploring iPhone Safari Web App: Discovering functions tailored for iPhone users

I am exploring the possibilities of accessing native iPhone features while developing a Web App using html/css/javascript and running it in Safari. I am curious to know if I can tap into smartphone-specific features, especially those unique to iPhone/iTou ...

Using Next.js to store the authentication token in memory and the refresh token in an HTTP-only cookie

Currently in the process of setting up an authentication flow using Next.js and an API with Express.js. The plan is to store a JWT token as an auth token in memory that can be refreshed periodically using a refresh token stored in an HTTPOnly cookie. To ...

What is the best way to eliminate elements from an array depending on whether their index is odd or even?

I am attempting to organize an array based on its odd and even indexes, then pass this data as a prop to another component. Here is my approach: The array I am working with is called products (data from WooCommerce). const products = [ { attributes: ...

Tips for Troubleshooting TypeScript Code in Chrome Instead of JavaScript Code?

Is there a more efficient way to debug TypeScript code in Chrome instead of JavaScript? Currently, I have been manually debugging every time from the start when writing code in Angular2 with WebStorm 11. ...

What is the best way to style nodes in a Force Directed Graph using CSS in D3?

Currently, I am developing a Force Directed Graph using D3 and managed to make it work with svg circles for the nodes. However, when attempting to use div elements along with CSS left and top properties, the positioning of the nodes seems to be incorrect. ...

Keep the true number hidden in the JavaScript array

Today while working on a script, I encountered an issue when trying to test it. The script was not returning the correct value - instead, it was showing [object Object] which was not the expected output. You can see a screenshot of the problem here. To res ...

What is the reason for the inability to access a global variable type variable outside of the $.each function when used within the $

While analyzing a code snippet, I came across an issue with a variable causing an error. function call(data) { $.each(data, function(index, value) { var ddlId = 'ddlCat' + data[index].docId; var html = '<tr id="supp_doc_row_&ap ...

I am facing an issue with updating the state dynamically within a useState object

Within my useState, there is an object containing a variety of values. I have an input field and am dynamically setting its value to useState[key], which works fine. However, the issue arises when I try to update these values. When I call onChange and use ...

An error occurred when trying to reopen a BrowserWindow after clicking a button in Electron, resulting in the destruction

Exploring the world of the Electron Framework, I am currently working on creating a basic desktop application. However, I have encountered an issue. Whenever I open a new window in my Electron app and then try to close it using the menu bar close button, ...

What are the implications of utilizing a query string in a POST request?

In our system, POST requests are sent from the frontend to the backend. Instead of using the body to pass data to the server, these requests utilize query strings in the URL params. It is important to note that these requests only contain string parameter ...

Is the code for uploading multiple images not functioning as expected?

My Photo Table is Column Name Data Type Constraint PhotoID Int Primary key,auto increment PhotoName Varchar(100) ExtName Varchar(100) PhotoType Varchar(100) PhotoSize Int TempleID Int Foreign key with templ ...

Response from the Facebook API regarding group information

I have integrated JavaScript SDK codes from the developers at Facebook. I am looking to retrieve my user's groups. <script> FB.api( "/me/groups", function (response) { if (response && !response.error) ...

Determining element visibility in React

Please refrain from flagging this as a duplicate. While it may be similar to other questions, I am specifically inquiring about the location to place the code, not how to write it. Here is the code I have and my goal is to determine which section is curre ...

Updating variable values using buttons in PHP and Javascript

I've implemented a like/unlike button along with a field displaying the number of likes. The code below uses PHP and HTML to echo the variable that represents the total number of likes: PHP-HTML: <span>likes: <?php echo $row['likes&apo ...

Encountered an error while attempting to execute the command npx create react app: spawn UNKNOWN error occurred

After attempting to execute a basic npx create-react-app, an unexpected error occurred: D:\>npx create-react-app abc npx: installed 67 in 4.255s Creating a new React app in D:\abc. Installing packages. This might take a couple of minutes. In ...

Transitioning from bootstrap 3 to 5 results in an increase in all sizes across the board

After transitioning from bootstrap 3 to 5, I noticed that all the elements on every page of my app became enlarged. The only component using bootstrap in this image is the dropdown menu with three vertical dots. https://i.sstatic.net/Ma27h.png https://i.s ...

Upon successful completion of the Ajax call, refresh the page without causing any blinking

Hey there, I'm facing an issue with my website, I've implemented ajax to fetch data from my API, and upon successful retrieval, I need to reload the page to display the information, However, sometimes the page blinks before reloading, while oth ...

Can someone help me figure out the issue with my Angularjs ng-repeat implementation?

After spending hours trying to figure out why something so simple is not working, I'm at a loss. Testing with a dummy list proves the functionality works, but when I connect my server-side data source, it fails. The JSON returned from the AJAX call i ...