Determine which function triggers the execution of a callback

I am conducting a test to determine in which function this callback function is executed. The expected result should be a boolean value. I trust that you understand my objective.

Below is an example of the code:

function test(par, callback) {
  // ...
  if (typeof callback == 'function') { 
    callback.call(this);
  }

}

test("par", function() {
  console.log("Test to see if in function test: " + "<if this is in function test>");
});

Does this bear any resemblance to instanceof?

Answer №1

A unique approach is required due to the deprecation of arguments.caller

function sample(param, cb) {
  // ...
  if (typeof cb == 'function') { // ensure the callback is a function
    cb.call(this);
  }

}

sample("param", function customCb() {
  var checkCaller = customCb.caller === sample;
  console.log("Checking if inside sample function: " + checkCaller);
});

Another unconventional method involves using error stacks:

var verifyCallback = function(funcName) {
  var e = new Error();
  var caller = e.stack.split('\n')[2].trim().split(' ')[1];
  return caller === funcName;
}

function wrap(){
  console.log(verifyCallback('wrap'));
}

wrap();

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

Can you explain the significance of this async JavaScript server application error?

While working on a weather app website connected to another site through a server, I encountered an issue with asynchronous JavaScript. Upon running the code, I received an error message stating "uncaught syntax error: unexpected end of input" in the last ...

Generate and store text inputted from contenteditable

As I embark on creating my own custom rich text editor, I have a couple of questions regarding its functionality. First and foremost, is it possible to prepopulate the text area with content? Additionally, I'm seeking guidance on how to save and utili ...

Adding Currency Symbol to Tooltip Data in Material-UI Sparklinechart

Below is a SparklineChart example using MUI library: import * as React from 'react'; import Stack from '@mui/material/Stack'; import Box from '@mui/material/Box'; import { SparkLineChart } from '@mui/x-charts/SparkLineCha ...

How come the "colspan" attribute is not functioning properly in my table?

Check out the simple table form I created on jsfiddle. Here is the code snippet: <table> <tr> <td class="field_label">name</td> <td>*</td> <td> <input type="text"> ...

Create a dynamic HTML page using JavaScript

When I click on the following links: How can I create a new page using JavaScript? Create and dynamically append elements I'm looking to dynamically add HTML elements with JavaScript within a div, but I don't want my code to become overly comp ...

Tips for displaying indentations on Tube Geometry using THREE.js

Currently, I have a project where I am tasked with displaying dents on a pipeline in a 3D format. To create the pipeline, I utilized THREE.js's tube geometry which is illustrated below: <!DOCTYPE html> <html lang="en"> <head> ...

What could be the issue with the nodeValue property?

// html <div>Welcome Everyone!</div> // JavaScript var textElement = div.firstChild; textElement.nodeValue = "Hello Everyone"; Here is the example: example Why is it not possible to modify the text content? ...

Is there a way to set an image as the background of my HTML screen?

{% extends "layout.html" %} {% block app_content %} <div> {% from "_formhelpers.html" import render_field %} <form method="post" enctype="multipart/form-data"> <div class = "container"> < ...

The event onmouseover triggers actions on elements contained within

I am facing an issue with a div that acts as a container for text: <div class="timeSpanWrapper" data-occupied="false"> <span>@day.ToString("HH:mm", new System.Globalization.CultureInfo("da-DK"))</span> </div> Upon hovering ove ...

Information is not appearing in the table

I'm having trouble displaying data in a table format. The issue arises when I try to fetch data from a JSON file using a custom service. The fetched data is then inserted into the $rootScope object. However, when I preview the view, it appears blank ...

Guide on modifying cube material dynamically in WebGL at runtime

Currently, I am utilizing three.js to create animations. My goal is to dynamically modify the material of a cube mesh. Below is an example: // Create cube geometry var material1 = [new THREE.MeshBasicMaterial({color:0xBEE2FF}),.....]; var geometry = new ...

Is React.js susceptible to XSS attacks through href attributes?

When user-generated links in an href tag appear as: javascript:(() => {alert('MALICIOUS CODE running on your browser')})(); This code was injected via an input field on a page that neglects to verify if URLs begin with http / https. Subseque ...

Issue with Textarea not updating when props change in a React component

I am facing an issue with updating the default value of a textarea based on props passed from a parent component. Strangely, the update works when using 'value' but not when using 'defaultValue'. However, I need the textarea to be edita ...

Images not showing in Vue.js

I have been working on setting up a carousel using bootstrap-vue. It is being generated dynamically through an array containing three objects with keys such as id, caption, text, and image path. The issue I am facing now is that while the caption and text ...

Button click does not fill in Jquery Datepicker?

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <link type="text/css" href="Styles/Site.css" rel="Stylesheet" ></link > <script type="text/javascript" src= ...

Tips for distinguishing between submit() and other JavaScript functions, and understanding why submit() may not be functioning as expected

In the table, I have a list of users with "update" and "delete" links added at the end of each line. To enable this functionality, I implemented a JavaScript function that captures the user ID, sets another field to "true," and inserts these values into a ...

Tips for refreshing an element after modifying a data-* attribute

I have an element that has the following CSS style: #element:after { content: attr(data-percent); } In an attempt to change the data-percent attribute using jQuery, I used this code: $('#element').data('percent', '50%'); ...

What is the best way to retrieve data from app.post within react.js?

//server.js app.post('/trip', function(req,res){ var params = "something"; getResult(params).then((db)=>{ // I am trying to access the variable called "db" in my App.js(React) file, but I am unsure of how to do so. res.s ...

Steps for sending a request to the root resource

I've encountered a problem that stems from my limited knowledge of Express. Despite creating a project with Express, I'm unable to make calls to the root, only to the routes. I suspect the issue lies in my usage of app.use(...). app.js var inde ...

What causes my local storage to be cleared whenever I refresh the page in React with Redux?

What causes my local storage to reset to empty whenever I refresh the page? I am attempting to save data to local storage that is also passed to my redux state, but I am unable to do so. const retrieveLocalStorage = () => { const oldExpenses = JSON ...