Caller Function's Parents in JavaScript

I have functions in JavaScript that need to verify if they are being called by the correct function (for example, it requires the function

something.stuff.morestuff.coolFunction
to initiate it). I attempted using Function.caller, but it only gives me the function itself without any information on its containing objects.

Consider the following scenario:

function helloWorld(){
    if(/* exact path of calling function */ === 'greetings.happy.classic.sayhello'){
        console.log('Hello World');
    }else{
        console.log(/* previous path */ + ' not permitted.');
    }
}

greetings = {
    happy: {
        classic: {
            sayHello: function(){ helloWorld(); },
            sayBye: function(){ helloWorld(); }
        }
    },
    angry: {
        sayHello: function(){ helloWorld(); }
    },
    simple: [
        function(){ helloWorld(); }
    ]
}
function sayWords(){
    helloWorld();
}

Desired output:

greetings.happy.classic.sayHello(); // => Hello World!
greetings.happy.classic.sayBye();   // => greetings.happy.classic.sayBye not allowed.
greetings.angry.sayHello();         // => greetings.angry.sayHello not allowed.
greetings.simple[0]();              // => greetings.simple[0] not allowed.
sayWords();                         // => sayWords not allowed.
helloWorld();                       // => null not allowed.
// unsure what would be returned here, so used null

The main question is:

How can I determine the complete object path (e.g., greeting.happy.classic.sayHello) of the calling function? Function.caller.name only gives the function name, which is insufficient. The entire hierarchy of the calling function's location is needed.

This seems like a complex issue, so thank you all for your assistance.

Answer №1

It appears that you are attempting to locate the parent's reference within the child object, which is not feasible. For further information, refer to this helpful post: How to Get the Parent of a JavaScript Object

Answer №2

One potential solution is to utilize the method new Error().stack in order to determine the origin of the call.

It's important to note that the effectiveness of this approach may be compromised by preprocessors, uglifiers, and bundlers that could potentially alter your code...

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

Angular SPA Routing for .Net Core 2.0

Having recently created a new Angular SPA project using the .Net core 2.0 SPA templates, I find myself facing some challenges as a newcomer to Angular/Typescript and HMR. While most functionalities were working smoothly at first, I noticed a peculiar issu ...

Significant delay in processing second jQuery Ajax call

Attempting a simple Ajax call with page content refresh using the following code snippet: $("a.ajaxify-watched").bind("click", function(event) { $item = $(this); $.ajax({ url: $(this).attr("href"), global: false, type: "G ...

React-beautiful-dnd does not function properly when used with the overflow auto property

Currently, I'm in the process of developing an application similar to "Trello" and have encountered a few challenges along the way. I've successfully created the main components such as the "Board," "Cards," and "Tasks." Each card has a fixed wid ...

Creating duplicates of a parent mesh in THREE.js with its children and additional materials

I am inquiring about a cloning issue I am having with a mesh that has a parent and 4 children, each with different materials. When I clone the parent mesh using this code: let result = cloudObjects.sideCloudGeometry[texture].clone(); The cloned mesh look ...

Invalid Resize Argument Causes Background to Not Appear on IE Browser

I have encountered a problem where the background (BG) image is not appearing in Internet Explorer (IE). I am struggling to find a solution for this issue. BG Problem Below is the code snippet showing how I implemented the background image. I have used a ...

When working with the Google Sheets API, an error occurred: "this.http.put(...).map is not a valid

Having difficulty with a straightforward request to the Google Sheets API using the PUT method. I followed the syntax for http.put, but an error keeps popping up: this.http.put(...).map is not a function. Here's my code snippet: return this.http ...

Function defined as an AngularJS component

I am facing an issue where my component is not initializing when I create it with a function that returns a component object. Can someone please help me understand the difference between these two situations? Html: <div ng-app="demoApp"> <navb ...

Ways to eliminate all characters preceding a certain character within an array dataset

I am currently working on parsing a comma-separated string retrieved from a web service in my application, which contains a list of user roles. My goal is to convert this string into an array using jQuery, and I have successfully achieved that. However, I ...

Why is my React component not being updated with Routes?

I'm new to using react-router and I'm struggling with it for the first time. Here is the code snippet: App.tsx import React from 'react'; logo = require('./logo.svg'); const { BrowserRouter as Router, Link, Route } = require ...

Is it best practice to store irrelevant context in a separate storage when utilizing the React Context API?

In the process of developing a web app, I have chosen to utilize the React Context API for managing state globally instead of opting for Redux. Currently, I have a store folder alongside my components folder where I store the loggedIn state. As I prepare t ...

Implementing a dynamic update of an HTML element's content with JSON data - Learn how!

My task involves creating a quiz application where I need to show the answers along with images of the choices stored in my JSON data. However, I encounter an error: Uncaught TypeError: Cannot set properties of null (setting 'src') when I attempt ...

Using the power of Javascript's jQuery library: the fantastic ".on()" Event Handler

I'm encountering an issue with the Jquery Event Handler ".on()". On my home page, I have a Favorite button on each post. If the post has not been favorited: li appears inactive Event 1 is triggered If the post has been favorited: li appears act ...

stream a song with a font awesome symbol

Can an audio track be played using a font awesome icon, such as displaying the song name (mp3) with a play icon right next to it? When users click on the play icon, can the track start playing and be paused or stopped at will? The list will consist of app ...

Retrieving JSON information using JavaScript

I am encountering an issue with the "Ion.RangeSlider" library. I am attempting to dynamically load values via JSON, but I am unable to get the slider to accept the data from the "from" field. It is important that the value is not hardcoded since the user h ...

Concealing the primary div within a Vue child component

Is there a way to conceal the primary div within a Vue application created using Vue-CLI? I attempted adding the display property, but it did not solve the problem. I am attempting to hide it within my Channels component. Here is how my main component lo ...

Is there a way to personalize the header outline of the mui-material datagrid?

Can someone help me modify the appearance of the Mui Datagrid outline to something different than its default setting? I'm having trouble uploading my code. Are there any reference materials or sample code snippets available for this modification? ...

Ways to verify if a user is authenticated without relying on request.session

I am currently developing a web application using Express, Docker, and following a Three-layered architecture. In my app, I store user login information in a session and have blogposts as a key resource. To retrieve the blogpostId from the database in the ...

Upgrading the entire document's content using jQuery

I am dealing with an ajax response that provides the complete HTML structure of a webpage, as shown below: <!DOCTYPE> <html> <head> <!-- head content --> </head> <body> <!-- body content --> </b ...

Firebug mistakenly detects phantom errors

<div id="video-player" data-src="http://www.youtube.com/embed..."></div> Inspect Element - Browser Developer Tools: Error: Access to property 'toString' denied I scanned the entire page (Ctrl+F) and could not find any reference t ...

Newbie's Guide - Building React/React-Bootstrap JavaScript Components Post Linking CDNs in index.html

Exploring Glitch hosting for a React/React-Bootstrap website as part of my web development training. Although these tools are new to me, I have years of experience as a developer. Successfully linked React, React-Dom, Babel, and React-Bootstrap CDN's ...