Is it possible to invoke this JavaScript function like this?

Is there a way to call a function like item_edit.say hello by passing it as a string on the window object (similar to the last line in the snippet below)?

var arc={ view: { item_edit: {} } };

arc.view.item_edit={
  say_hello: function(){
    alert('hello there');
  }

}

var f_name='say_hello';
var g_name='item_edit.say_hello';

var str=window.arc.view.item_edit[f_name]();  // <- this works
var str2=window.arc.view[g_name]();  // <- this is what I'm interested in; currently doesn't work

Do you have any suggestions on how to make this work?

Thank you in advance.

Update #1: I should mention that I probably don't want to use eval, although upon further consideration, it may actually be the most sensible approach (and is, in fact, what eval was designed for).

Answer №1

Yes, the Google closure library implements a similar functionality in its goog.provide method when not undergoing optimization by the compiler.

function getPropertyValue(obj, key) {
  var keys = key ? key.split('.') : [];
  var index, length = keys.length;
  for (index = 0; index < length - 1; ++index) {
    obj = obj[keys[index]];
  }
  var property = index < length ? obj[keys[index]] : obj;
  return property.apply(obj);
}

Additionally, on browsers where the Date.now function returns the current timestamp,

getPropertyValue(window, 'Date.now', [])

This will retrieve and return the current timestamp.

Answer №2

Here is a solution utilizing the .reduce() method.

var str2 = g_name.split('.').reduce(function(obj, key) {
    return obj[key];
}, window.arc.view);

To ensure compatibility with older browsers and add safety measures, some shim might be necessary.


If you find yourself performing this task frequently, consider adding the function to your library for future reuse.

function keyToObj(obj, key) {
    return obj[key];
}

You can then use it in this way:

var str2 = g_name.split('.').reduce(keyToObj, window.arc.view);

@MikeSamuel highlighted an issue regarding the context (this value) when using this method.

To address this, a specialized version tailored for method invocations could be created.

function keyToMethod(obj, key, i, arr) {
    return i === arr.length - 1 && typeof obj[key] === "function"
                              ? function() {
                                    return obj[key].apply(obj, arguments);
                                }
                              : obj[key];
}

This updated function returns a new function that executes the method from the correct object.

var str2 = g_name.split('.').reduce(keyToMethod, window.arc.view)();

Further enhancements could involve checking if the default this value is being used by the returned function and utilizing the provided value if not.

Answer №3

What do you think of the following:

let variableTwo = eval('window.arc.display.' + g_name + '()');

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

jQuery ajax issue: Unable to locate file using relative path

I have recently transferred some script from an HTML document to an external file. I updated the jQuery path to point to the new location of the JavaScript file, but now it is unable to locate the necessary PHP file. Can anyone shed light on why this might ...

Attempting to display a collection of 16 diverse images by utilizing the Math.random function in conjunction with a

I have been attempting to retrieve 16 random images, but I keep getting duplicates. I am aware that a modification needs to be made to the one => one.number filter, however all attempts so far have been unsuccessful. import React from "react"; import ...

Using Multer: Specifying multiple destinations with the destination property

I am facing a situation where I have to store images in multiple directories. To achieve this, I have configured multer as follows: app.use(multer({ dest: path.join(__dirname, '`public/assets/img/profile`'), rename: function (fieldname, ...

Ionic 2's Navigation Feature Failing to Function

I need to implement a "forgot password" feature on my login page. When a user clicks the button, they should be redirected to the "forgot password" page. Below is the code snippet from my login.html <button ion-button block color="blue" (cli ...

The GIF Loader fails to animate while an AJAX request is in progress

Displaying a DIV element containing a loading GIF image while waiting for an AJAX call response. Initially, the DIV element is hidden. Upon clicking a checkbox, the loader DIV is shown, followed by the completion of the AJAX call, and then hiding the load ...

How to prevent the parent element from scrolling when changing the value of a number input by scrolling

Within a container with fixed dimensions and scroll bars that appear when the content size exceeds the container, there is a form. This form contains an input of type "number" which allows changing its value using the mouse wheel. The issue arises when at ...

Capture any clicks that fall outside of the specified set

I am facing an issue with my navigation drop down menu. Currently, the pure CSS functionality requires users to click the link again to close the sub-menu. What I want is for the sub-menu to close whenever a click occurs outside of it. I attempted a solu ...

Is it possible to hide the <dd> elements within a <dl> using knockout's custom data binding upon initialization?

I have implemented a <dl> where the <dd> can be expanded/collapsed by clicking on the corresponding <dt> using knockout's data binding. The inspiration for my solution came from a tutorial on creating custom bindings. Currently, I h ...

A guide to JavaScript: Fetching and Parsing JSON Data from an API

Hey there! I've been working on using this code snippet in my defult.js file to call an API, but I'm having trouble figuring out how to read the output. It always seems to end up in the last else part. function fetchDataDist(APPID, flag, call ...

Learn how to send dynamic data to another HTML element using Ajax's success function

I received a successful ajax response from one HTML file, but I'm struggling to dynamically set the data from this response to another HTML file. Can anyone help me with this issue? Here is the code snippet from my ajax report: success: function( ...

The tooltip being displayed is plain and lacks any design elements

When I hover over my a element, only a simple tooltip appears without any styling, unlike what is shown in the Bootstrap documentation. (I am creating the a element using JavaScript) HTML <!DOCTYPE html> <html lang="en"> <head> ...

The code in check.js causes a square of dots to emerge on the screen in Skype

Trying to add a Skype call button to my page has been successful, but there's one issue - a pesky white dot keeps appearing at the bottom of the footer. The script source I used is as follows: <script src="http://download.skype.com/share/skypebu ...

What is the proper way to send an AJAX request with the data type set to

I am currently working on creating my own POST request. Below is the function I have written: function sendPost(o) { var h = new XMLHttpRequest(); h.onreadystatechange = requestComplete; function requestComplete() { if (h.readyState = ...

Eslint is not functioning properly on the local machine

Having trouble setting up eslint for my project. When I try to run eslint --init, I keep getting this error: /usr/lib/node_modules/eslint/lib/cli.js:18 let fs = require("fs"), ^^^ SyntaxError: Unexpected strict mode reserved word at exports.runInThis ...

When implementing asynchronous form control validation in Angular 2, several API requests are triggered

Can anyone help me with adding async validation using a FormControl? For every keypress, I am receiving multiple responses and it seems like an extra request is triggered whenever I type or remove a character in the form control. code-snippets.component.t ...

Module specifiers that are considered relative must always commence with either "./", "../", or just "/"

I need help with importing three.js. I have been following the documentation but I keep encountering an error message: Uncaught TypeError: Error resolving module specifier “three”. Relative module specifiers must start with “./”, “../” or “/ ...

Navigating through the realm of Android development entails understanding how to manage a multi-object function in JavaScript when using

In order to load an HTML page using the webview component and handle its functions, I am faced with a challenge. The HTML page contains a multi-object named (webkit.messageHandlers.adClicked). How can I utilize the webView.addJavascriptInterface() functi ...

Can studying Titanium Appcelerator enhance my comprehension of NodeJS?

As I dive into the world of building mobile JavaScript Applications in Titanium Appcelerator, I've come across documentation that mentions the use of the V8 Engine as their JS interpreter for Android. Additionally, some of the approaches seem to be in ...

Can Angular i18n facilitate language switching?

My objective is to switch the language from English (United States) to Indonesia using a button. View Source Code https://i.sstatic.net/0YlfWaCY.gif The issue is that the tutorial does not cover how to implement the language change feature. Why opt for ...

What is the best way to store a personalized configuration for a user within a Node module?

For my CLI project in Node.js utilizing commander.js, I am interested in implementing a way to store user-specific configuration settings. This will allow users to input their preferences only once during the initial usage. What would be the best approac ...