Creating a variable name from a string using a function

I am creating a log to keep track of the functions that are called. One specific function I am using is

record_activity( function_name );

I find it tedious to manually add this at the beginning of every function I want to monitor. Currently, my functions are structured like:

Object.Key.Func = function() { ... }

I have come up with a solution which seems to be working, but I am unsure about its implications:

function sub ( variable, func ) {
    var temp_func = function ( args ) {
        record_activity( variable );
        return func.apply(this,arguments);
    }
    eval( variable + ' = ' + temp_func );
}

sub( 'Object.Key.Func', function (name) { alert('hi ' + name) } );
Object.Key.Func('test');

If there is a method to achieve this without using eval, I would greatly appreciate it.

Thanks

Answer №1

To monitor the behavior of specific functions, you can implement wrapper functions for each one. Below is a snippet of code that demonstrates how to achieve this:

var counter = {};
// This function records activity for a specified function.
function record_activity (f, func_name, args) {
    counter[func_name] = counter[func_name]===undefined ? 1 : counter[func_name]+1;
}

// Define an object with functions to track: obj.foo and obj.bar
var obj = {
    a: 3,
    foo: function () {
        console.log("foo");
    },
    bar: function (b) {
        console.log("bar", this.a, b);
    }
};

// Create wrapper functions for tracking function calls
function create_func (f, func_name) {
    return function () {
        record_activity(f, func_name, arguments);
        f.apply(obj, arguments);
    };
}
for(var prop in obj) {
    if (typeof obj[prop] === 'function') {
        // Wrap the original function with the tracking functionality
        obj[prop] = create_func(obj[prop], prop);
    }
};

// Test the wrapped functions
for (var i = 0; i < 3; i++) {
    obj.foo();
};
for (var i = 0; i < 10; i++) {
    obj.bar(i);
};

console.log(counter);

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

Adjusting the backdrop hues

My goal is to change the background colors of my website by cycling through all possible combinations. However, I'm encountering issues with my code and can't figure out what's wrong. var red = 0; var green = 0; var blue = 0; do { do ...

Adjustable annotations in flot chart

When creating a flot, I can draw segments by specifying the markings in the options. markings: [ { xaxis: { from: 150, to: 200 }, color: "#ff8888" }, { xaxis: { from: 500, to: 750 }, color: "#ff8888" } ] Now, I am looking to remove these existing m ...

JavaScript Character Set on the Dynamic Page in Delphi

Within my Delphi application, I am dynamically generating HTML content. Displaying UTF-8 encoded strings in the webpage body is not an issue for me as I use HTMLEscape to encode regular strings (ensuring all strings in the list are properly escaped). The ...

The Vue design is not being reflected as expected

Encountering a peculiar issue where the style in my Vue component is not being compiled and applied alongside the template and script. Here's the code snippet: To achieve an animated slide fade effect on hidden text upon clicking a button, I've ...

Inspection Techniques for Javascript Objects

Is there a way to display an object's properties and methods in an alert box? When I try alerting an object, it only shows the nodename: alert(document); I'm looking for a way to see all the details of the object in the alert message. Is there ...

I noticed that the node_modules folder has mysteriously vanished from my

When I tried running npm install in the terminal of VS Code. PS D:\work\backEnd> npm install npm WARN old lockfile npm WARN old lockfile The package-lock.json file was created with an older version of npm, npm WARN old lockfile so ...

Establish a cookie using the PHP session's username

I have successfully implemented a general cookie for a one-time use scenario. However, I now need to create a cookie based on the username so that a message is displayed only once per user. My approach involves setting up a PHP session for the username ass ...

Angular 2 - Karma is having trouble locating the external template or style file

The file structure for this project (taken from the Angular 2 official site) is as follows: https://i.stack.imgur.com/A6u58.png Upon starting Karma, I encountered errors indicating that two files were not found under /@angular/... To resolve this issue, ...

The x-axis values in Amchart are transitioning rather than shifting

I'm facing an issue with my x-axis values as I'm using real-time amcharts. The x-axis values change every 3 seconds, but instead of smoothly moving, they abruptly change to the next value. I would like it to slide smoothly like this example: htt ...

Did you manage to discover a foolproof method for the `filesystem:` URL protocol?

The article on hacks.mozilla.com discussing the FileSystem API highlights an interesting capability not previously mentioned. The specification introduces a new filesystem: URL scheme, enabling the loading of file contents stored using the FileSystem API. ...

Is it possible to define a variable within a JavaScript function and then access it outside of the function?

I have a Node.js application where I need to define a variable inside a function and access its value outside the function as well. Can someone provide guidance on how to achieve this in my code? var readline = require('readline'); var rl = read ...

Why is there an issue with the way I am defining this Javascript variable?

In my JavaScript file, milktruck.js, I have defined an object called TruckModel. My goal is to create an array of TruckModel objects because in my multiplayer game, I cannot predict how many players will enter or exit at any given time. The issue I am fa ...

Guide on automatically opening downloaded files in a new tab in IE 11 or Edge similar to the way file downloads function in Chrome

I am currently using Windows 10 and implementing msSaveOrOpenBlob in JavaScript to download the AJAX call blob on IE11. I want the PDF file to be opened in a new tab without any prompts, similar to how it works in Chrome. However, even when trying with th ...

Utilizing aria-expanded="true" for modifying a CSS attribute: A simple guide

I am looking to utilize aria-expanded="true" in order to modify a css property such as an active class : <li class="active"> <a href="#3a" class="btn btn-default btn-lg" data-toggle="tab" aria-expanded="true"> <span class="networ ...

Utilizing Weather APIs to fetch JSON data

Trying to integrate with the Open Weather API: Check out this snippet of javascript code: $(document).ready(function() { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(function(position) { $(".ok").html("latitude: " + ...

Storing data across app sessions without the need for an external file

Currently, I am developing an application that allows users to input text strings. It is important for me to be able to save these strings even when the program is closed and reopened. In order to achieve this, I am looking for a way to encapsulate a dat ...

Is Eslint functioning in just one Sublime Text project?

I have encountered an issue where I duplicated the .eslintrc and package.json files for two projects, but only the first project is able to run linting properly. The second project does not show any errors. I am using sublime-linter with the eslint modul ...

Is there a way to submit a form without navigating away from the current webpage?

I'm working on a registration form and I need help figuring out how to send the input information to the action.php file without the user being redirected to it. Is there a way to have the form submitted in the background and then redirect the user ba ...

Access a specific JSON value using AngularJS

When using AngularJS to read a specific JSON value, I encountered the following issue: $http({method: 'GET', url: urlVersion}). success(function(data, status, headers, config) { console.log("success data " + status); $scope.ext = data.ve ...

Enhancing gallery user experience with jquery to animate the opacity of active (hovered) thumbnails

I am attempting to create an animation that changes the opacity of thumbnails. By default, all thumbnails have an opacity of 0.8. When hovered over, the opacity should increase to 1 and then return to 0.8 when another thumbnail is hovered over. Here is th ...