Modify the function name and parameters as needed (such as in the `.getString()` method)

tl;dr:

I am looking to modify the appearance of a function, specifically in how it is displayed when using `console.log` in browsers like Firefox or Chrome. My goal is to alter the arguments and name that are shown, as well as adjust properties such as `.length` and `.name`. Is this achievable?

The longer version :

I aim to replicate and customize the behavior of a specific function by injecting additional instructions before and after its execution. Below is an example of my code:

function customizeFunction(funcToCustomize) {
    return function(...args) {

        // Additional instructions, for instance:
        console.log('Calling', funcToCustomize.name);

        // The actual function execution
        let returnValue = funcToCustomize.call(this, ...args); 
                          // Or simply funcToCustomize(...args) if preferred
        
        // Instructions upon completion of the call :
        console.log('success, no error encountered during call');

        return returnValue;
    }
}

I have tested this code snippet in the Firefox console with the following input:

let original = function (x,y) {
    console.log(x+y);
};
let custom = customizeFunction(original);
custom(2,3);

/* Output :
Calling original  
5  
success, no error encountered during call debugger eval code:12:17  
undefined
*/

The functionality works correctly. However, whenever I execute:

console.log(custom);

The output displays function customizeFunction(args) instead of function original(x,y). Are there properties that can be adjusted to show either function original(x,y) or function custom_original(x,y) ?

Furthermore, while original.length returns 2, custom.length shows 0. Is there a way to modify this value as well?

Answer №1

Consider modifying the toString method of the function being returned

function personalizeFunction(funcToPersonalize) {
    let customizedFunc = function(...args) {

        // Implementing certain instructions, for instance:
        console.log('Calling', funcToPersonalize.name);

        // The actual function execution
        let returnValue = funcToPersonalize.call(this, ...args); 
                          // Another option is funcToPersonalize(...args) if preferred
        
        // Actions to take after executing the function :
        console.log('Success, no errors were encountered during call');

        return returnValue;
    }

  customizedFunc.toString = function () {
    return funcToPersonalize.toString();
  }

   return customizedFunc;
}

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

Attempting to create an endless scroll feature using a pre-existing list of div elements that are already present in the HTML

Struggling with jQuery, I want to implement an infinite scroll feature on my page using the existing divs. My goal is to have these divs appear and load randomly as the user reaches the end of the initial content. However, being new to jQuery, I'm uns ...

Set the height of the vertical scroll at a fixed 100% floatValue

Check out my creation at http://jsfiddle.net/ZygnV/ html, body { margin: 0; padding: 0; height: 100%; } .main-content-wrapper { height: 100%; overflow-y: hidden; white-space: nowrap; } .main-sidebar { display: inline-block; height: 1 ...

Why is $(window).load() being executed twice?

When using $(window).load() to resize images in a thumbnail gallery and set up a slideshow, the code seems to be running twice. This can be observed by noticing that a div is being wrapped around another div twice when inspecting the HTML on page load. Af ...

Using JavaScript to combine multiple arguments into one variable

Can multiple arguments be passed using a single variable? For instance, if I want to achieve the following: function foo(x,y){ document.write("X is " + x); document.write("Y is " + y); } var bar = "0,10"; foo(bar); The mentioned example is a sim ...

step-by-step guide to capturing test cases in Internet Explorer with Selenium

I am a beginner with Selenium automation testing. The application I'm working on is limited to Internet Explorer compatibility only. While I understand that we can run test cases in different browsers using respective drivers, I'm curious if th ...

Turn off all pointer events on the overlaying div but keep scrolling enabled

Issue: I am facing a problem with two containers that have overflowing text content like this: https://i.sstatic.net/wsasV.png In this setup, the blue <div>s have overflow:hidden applied. Now, I am trying to synchronize the scrolling behavior of th ...

What is the best way to securely store JWT tokens in React JS in order to authenticate access to different backend routes within an app?

In my project, I am utilizing the JWT token for authentication and authorization purposes. Post-login, I need to store the token value in the frontend (React JS) to be able to send it to the server for validating various routes in Node.js based on differ ...

Discovering every element on a webpage

Searching for elements in a webpage can be done using different methods. document.getElementsByTagName('*') and document.all Are there any other more efficient ways or are these two the most recommended? I am currently working on an element se ...

A guide on incorporating Carousel.Item within another component

Working on a carousel using react-bootstrap and the current code is functioning as expected: function App() { return ( <div className="App"> <h1>Hello CodeSandbox</h1> <h2>Start editing to see some magic ...

What is the best way to align a <div> element below another without being on the same line?

I'm currently working on developing a snake game. My focus right now is figuring out how to make the body parts of the snake follow the head and be positioned after it. <!--Player--> <div class="snake"></div> So here we have the sn ...

Is it better to convert fields extracted from a JSON string to Date objects or moment.js instances when using Angular and moment.js together?

When working on editing a user profile, the API call returns the following data structure: export class User { username: string; email: string; creationTime: Date; birthDate: Date; } For validating and manipulating the birthDate val ...

Link Javascript .append() variable to PHP variable

How can I save the 'money' variable from JavaScript as a PHP variable on the same page? JS $(document).ready(function(){ var money = 0; $(".target").change(function () { var optionSelected = $("option:selected", this); money = optionSelected.a ...

Insert a new <tr> element into a dynamic table using PHP and jQuery without the need to refresh the page

I am attempting to dynamically insert a row into an existing table when a button is clicked. The rows in the table are created dynamically based on data retrieved from a PHP script. My approach involves making an ajax call to the insert_tr.php script, whi ...

Output the contents of a nested object

After setting up a variable containing music library data... var library = { tracks: { t01: { id: "t01", name: "Code Monkey", artist: "Jonathan Coulton", album: "Thing a Week Three" }, t02: { id: " ...

Traversing a hierarchical JSON structure reminiscent of a tree object

I am working with a complex object structure, var cObj = { name: 'Object1', oNumbers: 3, leaf: [ { name: 'Inner Object 1', oNumbers: 4, leaf: [] }, { name: 'Inner Object 2', oN ...

Tips for enhancing the efficiency of a three.js environment within Gatsby.js or react:

I am dealing with a straightforward three.js scene that is rendered using an useEffect hook. The scene loads a model using GLTFLoader(). On the page, there are three event listeners triggered on load. One calculates the browser's inner height, anothe ...

Why does this JSX only display the most recent item I included in the object?

Within my function for constructing a search filter, there is the following logic: const filter = { $and: [ req.query.category !== "" ? { category: req.query.category } : {}, req.query.subCategory !== "" ? { ta ...

Issue with sending array as parameter in ajax call in Laravel

I am currently encountering an issue while attempting to pass an array through an AJAX request. <input type="text" name="item_name[]"> <input type="text" name="address"> $(document).on('click', '#save_info', function () { ...

Utilizing Knockout JS: How to effectively bind an entire object instead of separate values

This code snippet adds a checkbox next to each item in a list. When the checked status is changed, it will add or remove that value from the SelectedItems array: <script type="text/x-jquery-tmpl" id="tmpl"> <input name="cSelect" t ...

Sending a variable between two separate ajax functions in different pages

I'm having some trouble sending the Rest_ID to another page and using it in an Ajax call to fetch data from a database. Everything seems to be working fine, but I can't seem to access the value of Rest_ID. Here is the JavaScript document for fet ...