Executing a function on the window object in JavaScript

I have come across the following code and am seeking guidance on how to get the last line to function correctly. The API I am using currently employs _view appended as its namespacing convention, but I would prefer to switch to something like arc.view.$function_name. Thank you!

var arc={};
arc.view={
  say_hello: function(){
    alert("I want to say hello");
  }
}
function say_goodbye(){
  alert("goodbye to you");
}

arc.view.say_hello(); // works
window['say_goodbye'](); // works
// Is it possible to make this work?
window['arc.view.say_hello']();

Answer №1

window['arc']['view']['greet_person']();

alternatively

window.arc.view.greet_person()

or

window['arc'].view['greet_person']()

You can use either the dot syntax or bracket syntax to achieve the same result. Dot syntax is simply a shorthand version of using brackets for property lookup, so all three examples above are equivalent. The bracket syntax should be used when the property name is dynamic or would cause issues with the dot syntax. For example:

var dynamicMethodName = someObject.getMethodName();
someOtherObject[dynamicMethodName]();

or

someOtherObject["a key string with spaces and {special characters}"]();

Answer №2

Give this a shot:

jsFiddle link

window["arc"]["view"]["say_hello"]();

Answer №3

When utilizing the square bracket notation, you are essentially calling a function within the window object named arc.view.say_hello, instead of a function within the "view" property of the object "arc". To clarify:

window["arc.view.say_hello"] = function () { alert("hi") };

window["arc.view.say_hello"](); // "hi"

If you intend to invoke a function as described, you must unravel the chain of objects. One approach is to create a utility function for this purpose. For instance:

var arc={};
arc.view={
  say_hello: function(){
    alert("I want to say hello");
  }
}
function say_goodbye(){
  alert("goodbye to you");
}

function call(id) {
    var objects = id.split(".");
    var obj = this;

    for (var i = 0, len = objects.length; i < len && obj; i++)
        obj = obj[objects[i]];

    if (typeof obj === "function")
        obj();
}

call("say_goodbye");
call("arc.view.say_hello");

The utility function can be extended to utilize arguments or simply return a reference to the 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

How can I reduce the burden of dependencies on users with a pre-built NPM package?

I recently took over maintenance of an NPM package. It has a unique setup where the main file is located in the 'dist/' directory and it's built using webpack (via 'npm run build'). While this works for us, installing this package ...

I need to find a way to transfer user input data from the frontend to ExpressJS in order to make an API call using an endpoint

Within my perspective, there is a text box where users can input values. Leveraging jquery, I retrieved the user's value and now aim to transfer it from my jquery file to the express module in app.js. Any ideas on how to best approach this? ...

Error: The iOS 14.2 system is unable to locate the variable "webkit."

Currently, I am developing a web application using AngularJS 1.7. The app runs smoothly on Safari with iOS versions 12, 14.0, and 14.1. However, upon upgrading my iOS to version 14.2/14.3 (tested on both), I encountered the following error: Error: Referen ...

The problem arises when trying to use the Jquery click event on buttons that have been generated

I've encountered an issue where I can create components dynamically, but the click event doesn't seem to work on buttons that are dynamically generated. Check out the code snippet below: HTML file: <div class="merge_sections">&l ...

Looking to extract data from a Json object and add it into a table

<!DOCTYPE html> <html> <head> <script type="text/javascript"> function displayJsonData() { var jsonData = { "cars": [ '{"model":"Sentra", "doors":4, "features":["hi"," ...

Tips for resolving Vue.js static asset URLs in a production environment

I included the line background-image: url(/img/bg.svg); in my CSS file. During development mode, this resolves to src/img/bg.svg since the stylesheet is located at src/css/components/styles.css. However, when I switch to production mode, I encounter a 40 ...

JS implementing a listener to modify a Google Map from a separate class

Currently, I am in the process of migrating my Google Map functionality from ionic-native to JavaScript. I am facing an issue while attempting to modify the click listener of my map from a separate class. The problem seems to be related to property errors. ...

Is passportjs responsible for managing user registration?

Is it possible to utilize Passport for user signup if I am storing user information on a self-hosted server and cannot find a user signup function in the Passport.js documentation? ...

What is the best way to include a file attachment using a relative path in Nodemailer?

I am currently utilizing the html-pdf converter plugin to transform an HTML page into a PDF file. After conversion, this plugin automatically saves the PDF to the downloads folder. When I attempt to attach a PDF to a nodemailer email, my code looks someth ...

Selecting the optimal data structure: weighing the benefits of using boolean check versus array .include (balancing performance and redundancy

My objects can have one or more properties assigned, with a total of 5 different properties in my case. To illustrate this, let's use a simple movie example where each movie can be assigned from 5 different genres. I have come up with two methods to ...

Can dates in the form of a String array be transmitted from the server to the client?

Struggling to send a String array from the server side to the client using Nodejs and Pug. Encounter errors like "SyntaxError: expected expression, got '&'" or "SyntaxError: identifier starts immediately after numeric literal". Server runs o ...

Attempting to grasp the sequence in which setTimeout is ordered alongside Promise awaits

I've been puzzling over the sequence of events in this code. Initially, I thought that after a click event triggered and Promise 2 was awaited, the for loop would resume execution once Promise 1 had been resolved - however, it turns out the outcome is ...

Ways to conceal the picture

Check out the JSfiddle link here for the full code. I'm having trouble with my slider as the last picture keeps collapsing underneath and is not hidden as it should be. I suspect this issue is causing the slider to malfunction. HTML <div class=" ...

Incorporating server-side rendered components into a Vue.js parent component

I have a server-side rendered page that includes information about "orders" and a root Vue object initialized as the "parent object." Is it feasible to assign the rendered HTML orders as children of that parent Vue object? Vue.js is known for its dynamic ...

axios: prevent automatic sorting of objects according to keys

When using axios, I am receiving an API response. To send the sorted API response based on name, I use the following endpoint: http://localhost:8000/api/ingredients/ordering=name The actual object received from my server looks like this: { 2:{"id":2 ...

Next.js API Endpoint Call Resulting in Empty Object Returned by Fetch Function

Having an issue with making an API call in Next.js to delete an item from the database. I'm using the "body" field of the fetch to send a string to the API. The fetch call is within a Next.JS page, and the API endpoint is located in the API folder gen ...

fluctuating random percentage in JavaScript/jQuery

I am currently faced with the challenge of selecting a random number based on a given percentage ranging from 0 to 5. 0 - 25% (25/100) 1 - 25% (25/100) 2 - 20% (20/100) 3 - 15% (15/100) 4 - 10% (10/100) 5 - 5% (5/100) However, there are instances where ...

`I'm encountering issues when trying to pass an array through localStorage into a new array`

This is a complex and detailed question that I am struggling to find a solution for. Despite using deprecated mysql due to hosting limitations, the problem lies elsewhere. Part 1 involves dataLoader.php, which queries the database and retrieves posx and p ...

Oops! It seems like there's a problem with reading the 'strEmail' property of undefined. Do you have any ideas on how to fix this issue

Currently, I am working with Express.js to create a straightforward login post request. Here is the code snippet: app.post("/login", (req, res) => { res.send( { isUserRegistered: userLogin(req.body.strEmail, req.body.strPassword), ...

How to resolve the issue of not being able to access functions from inside the timer target function in TypeScript's

I've been attempting to invoke a function from within a timed function called by setInterval(). Here's the snippet of my code: export class SmileyDirective { FillGraphValues() { console.log("The FillGraphValues function works as expect ...