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

What is the best way to reset a dropdown list value in angular?

Is there a way to erase the selected value from an Angular dropdown list using either an x button or a clear button? Thank you. Code <div fxFlex fxLayout="row" formGroupName="people"> <mat-form-field appearance=&quo ...

Customizing the styling of a TextField component in ReactJS using material-ui

I am currently working with Reactjs and material-ui. I am looking to apply some custom styles to a TextField using css. Specifically, I would like to change the color of the TextField underline and label when the input is clicked. Although I know it can b ...

Implementing a 'Load More' button for a list in Vue.js

I am currently working on adding a load more button to my code. While I could achieve this using JavaScript, I am facing difficulties implementing it in Vue.js. Here is the Vue code I have been working with. I attempted to target the element with the compa ...

steps for linking a directive variable to a controller

Encountering an issue with 2-way binding in Angular where changes made to the input do not reflect in the controller. However, the initial value set by the controller does affect the directive. In the screenshot, a value was changed but vm.date still hold ...

What is the best way to invoke an API two times, passing different parameters each time, and then merge both responses into a single JSON object using a callback function?

This code snippet is currently functional, but it only retrieves the JSON response for the first set of parameters. I am looking to make multiple calls to an external API with different parameters and then combine all the responses into one concatenated J ...

Combining Rails 4 with coffeescript while encountering an issue with the jQuery sortable detatch functionality

Currently, I am using Ruby on Rails 4 along with the jquery-ui-rails gem. Within my application, there are certain lists that have a sortable jQuery function implemented. $ -> $('#projects').sortable handle: '.handle' ...

Using Express to Deliver Static Content to Subdirectories

I am currently using Express to serve a React application that was bootstrapped with Create React App. The project has the following directory structure: |--client/ | |--build/ | | |--static/ | | | |--main.css | | | |--main.js | ...

I am encountering difficulties displaying the image and CSS files from another folder in my HTML with Node.js

I am facing difficulty in establishing a connection between my front-end and back-end using node.js. As a result, the website only displays the HTML code without linking to the CSS or image files. Here is the folder structure: root -src •pi ...

Show or hide the expand/collapse button based on the height of the container

Looking for a way to hide content in a Div if it's taller than 68px and display an expand option? The challenge lies in detecting the height of the responsive Div, especially since character count varies. I attempted using PHP to count characters bu ...

Searching for specific data within an embedded documents array in MongoDB using ID

While working with mongodb and nodejs to search for data within an embedded document, I encountered a strange issue. The query functions as expected in the database but not when implemented in the actual nodejs code. Below is the structure of my data obje ...

What is the best way to retrieve and parse XML using node.js?

Is there a way to fetch an XML file from the internet using node.js, and then parse it into a JavaScript object? I've looked through the npm registry but can only find examples on parsing XML strings, not fetching them. ...

Next.js encountered a Runtime Error: Trying to access properties of undefined (specifically 'status') and failing

For those interested in viewing the code, it can be found here During the creation of a portfolio website using Next.js, I encountered an error. I am utilizing the latest version of Next.js (next 13.4.16) and incorporating the app router into my project. ...

Japanese Character File Naming Convention

When dealing with certain Japanese characters, the content disposition header appears as follows: Content-Disposition: attachment; filename=CSV_____1-___.csv; filename*=UTF-8''CSV%E3%82%A8%E3%83%93%E3%83%87%E3%83%B3%E3%82%B91-%E3%82%B3%E3%83%94%E ...

Unable to retrieve variable using the require statement

When attempting to access the variable 'app' from the required index.js in my test, I encounter difficulty resolving the 'app' variable. server.js 'use strict'; var supertestKoa = require('supertest-koa-agent'); ...

Generate a compressed file from a readable source, insert a new document, and transfer the output

The objective is to obtain an archive from the client, include a file, and transfer it to Cloud Storage without generating a temporary file. Both the client and server utilize the archiver library. The issue with the code snippet provided is that the file ...

Issues with jQuery chaining and toggle not executing as expected

When running this code snippet, var waitRow = $(this).parent().parent().next().get(0); $(waitRow).children('td:nth-child(2)').html('some text').toggle(); the toggle function seems to be ineffective. However, by modifying the code as ...

Passing data retrieved from fetch requests in ReactJS using context: Best practices

Just started learning React and need some help. I'm trying to pass variables with json data to a component for further use but running into errors. What changes should I make to use variables with json data from Store.js in the product.js component? T ...

Should I use React with Spring Boot or just Spring Boot for this project?

My partner and I are collaborating on a project for our current semester course. As we delve into our research on potential technologies to use, it seems like Spring Boot for the server side along with MySQL or Postgres for the database are emerging as s ...

The ng-model failed to display the updated value until a click was made somewhere on the page

I am struggling with displaying the correct value of an ngModel variable defined in my controller. Despite changing to the correct value in the console, it doesn't update on the page until I click somewhere else or hit the update button again. Here&a ...

Transfer information to an ExpressJS server in order to display a fresh view

I'm struggling to figure out how to transfer data from the client side to an ExpressJS server in order to generate a view based on that information. When users choose different parameters on the client side, they update the 'data-preference&apos ...