Retrieve the function reference of a class (not an instance)

I am working on a code that involves using a function to alter existing functions and return a reference to a new function. I aim to apply this function to specific methods within a class. The current state of my code is as follows:

function modifyMethod(func) {
  return function() {
    console.log('working');
    return func.apply(this, arguments);
  };
}

function modifyClassMethods(ClassName, methodArray) {
  // Implementation pending 

  return ClassName;
}

class Temp {
  hi() {
    console.log("hi method");
  }
}

Temp = modifyClassMethods(Temp, ["hi"]);
const temp = new Temp();
// The expected output is
//
// working
// hi method
temp.hi();

When attempting to invoke the modifyMethod with Temp.hi, the func parameter appears to be undefined. Even if an object is created and then the method is modified, the changes will only affect that particular object's method, not all objects within the same class.

It should be noted that this example serves as just a demonstration. My goal is to extend this modification to the methods of various classes. Therefore, it is not possible to generalize method names either. Any suggestions or code snippets for the modifyClassMethods would be highly appreciated.

Answer №1

When defining methods with method syntax within a class, it's important to note that those not marked as static are considered prototype methods. Therefore, they belong to Temp.prototype rather than directly to Temp. This means that any updates should be made on Temp.prototype:

Temp.prototype.hi = modifyMethod(Temp.prototype.hi);

Static methods, on the other hand, are the only ones that reside on Temp itself.

In some cases, you may encounter functions created within the class body using the syntax of the class fields proposal:

class Temp {
    hi = () => {
        //
    };
}

These are known as instance methods. They are generated by the constructor and duplicated for each instance, as if they were constructed in this manner:

class Temp {
    constructor() {
        this.hi = () => {
            //
        };
    }
}

Wrapping these methods is only possible after an instance has been created since they are specific to each instance.

In summary, let's consider the following example:

class Temp {
    static staticMethod() {
        // ...
    }
    prototypeMethod() {
        // ...
    }
    instanceMethod = () => {
        // ...
    };
    constructor() {
        this.anotherInstanceMethod = () => {
            // ...
        };
        this.yetAnotherInstanceMethod = function {
            // ...
        };
    }
}

This class showcases three types of methods:

  • Static Methods, like staticMethod, accessible through Temp (e.g., Temp.staticMethod);
  • Prototype Methods, such as prototypeMethod, located on Temp.prototype (e.g., Temp.prototype.prototypeMethod); and
  • Instance Methods, including instanceMethod, anotherInstanceMethod, and yetAnotherInstanceMethod, present on instances themselves when created.

¹ In reality, these methods are generated using Object.defineProperty as demonstrated below:

class Temp {
    constructor() {
        Object.defineProperty(this, "hi", {
            value: () => {
                //
            },
            writable: true,
            configurable: true,
            enumerable: true
        });
    }
}

To maintain simplicity, I used basic assignment in the examples provided earlier. :-)

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

Guidelines for utilizing regex to match this specific string

Hey guys, I need help with parsing this string (a url). example.html/#playYouTubeVideo=id[lBs8jPDPveg]&width[160]&height[90] I'm trying to extract the values for id, width, and height within brackets. This is what I've come up with: [ ...

What is the process for creating a server-side API call?

I've designed a front-end application that uses an API to retrieve data. The problem I'm facing is that in order to access the API, I need to use an API Key. If I include the API key in the client-side code, it will be visible to users. How can I ...

Learn how to insert a <TableRow> in a for loop using Object.keys

<TableBody> {(() => { var result = []; let key = Object.keys(genericResultList)[1]; var list = genericResultList[key]; for (var i = 0; i < list.length; i++) { ***\<!-- Add in the \<T ...

Issue with slideshow counter persisting across multiple arrays

I am experiencing an issue with my simple slideshow type application where it consists of multiple parts on the page. Each slideshow has its own array containing specific information for each slide. The problem arises when I cycle through one slideshow to ...

Prevent ng-click functionality for markers and infowindows on an Angular map

Currently, I am utilizing angular map and have bound an ng-click event to it which triggers a dialog window to open. However, I am facing an issue where I want to disable ng-click for markers and infowindows. This problem did not arise when I was using pla ...

Enforce uniqueness on two fields with a MongoDB composite unique constraint

Within my car database in MongoDB, I store information about user_id and default_car fields. Each user is allowed to have a single default car, but can also have multiple non-default cars. For example, this data structure would be considered valid: [{user_ ...

Ways to prevent the execution of JavaScript code?

I have a website that contains a block where AJAX-loaded code is coming from a remote server. How can I prevent potentially harmful code from executing, especially when it originates from a remote source? Is using the "noscript" tag sufficient to protect a ...

Is it not possible to access a private member from an object that was not declared in its class...?

Within this program: class Example { #privateMember = 123; // these are fine addNumber (n) { return this.#privateMember + n; } doAddNumber (n) { return this.addNumber(n); } // "cannot read private member #privateMember from an ...

Step-by-step guide on transferring an HTML5 sqlite result set to a server using AJAX

Imagine I have a scenario where I receive a result set as shown below: db.transaction( function(transaction) { transaction.executeSql( 'SELECT col1, col2, col3 FROM table;', [],function(transaction, result){ //need to find a ...

Attempting to use vue-test-utils-getting-started with the standard configuration results in a "Preset Not Found" error during

Currently, I am in the process of conducting a unit test by referring to the official guide provided. To do so, I have cloned the demonstration repository named vue-test-utils-getting-started. To replicate the issue, follow these steps: After cloning vu ...

SquirrelFish appears to be lacking "bind()", so how can one attach a JS callback to "this" in its absence?

Does anyone know a way to attach a JS callback to "this" without using "bind()"? Based on Samsung specifications: In 2013 with V8: everything functions as expected (refer to linked screenshot, too large to include here) In 2012 with SquirrelFish: encoun ...

What impact does rotation have on an orthographic camera within the Three.js framework?

I am working in Three.js with a scene that includes a plane and an orthographic camera. Orthographic camera at -90deg: When the camera is rotated to -90 deg on the x-axis (looking straight down from above), only the plane is visible in the view. Scene s ...

Dynamically alter routing in Express by retrieving route paths from a JSON document

My goal is to dynamically update my route in Express using a JSON file that stores the specific link. The JSON data resides in articles.js and appears as follows: title: 'title1', link: 'title2', creator: 'user1', crea ...

Connecting MySQL to HTML: Step-by-step guide

I am currently working on building a website through coding in HTML using gedit. My goal is to have a login or registration feature on the homepage, which will then direct users to their own personalized page on the site. On this page, they should be abl ...

Determining the height of dynamically rendered child elements in a React application

Looking for a way to dynamically adjust the heights of elements based on other element heights? Struggling with getting references to the "source" objects without ending up in an infinite loop? Here's what I've attempted so far. TimelineData cons ...

Validating Cognito credentials on the server-side using Node.js

I am currently developing server-side login code for AWS Cognito. My main goal is to verify the existence of a user logging into the identity pool and retrieve the attributes associated with them. With email login, everything is running smoothly using the ...

Express.js returning unexpected results when calling MySQL stored procedures

I've encountered a strange issue with a stored procedure called getUsers in MYSQL. When I execute the procedure in phpmyadmin, it returns a table of users with their data perfectly fine. However, when I try to call the same procedure from my Node.js a ...

Do <script> tags in javascript provide an efficient way to parse Handlebars data?

I have a backend server.js code where I am selecting data from my database and then passing it to a handlebars file to be rendered in a table format. Here is how the handlebars file looks: <table> <tr> <th ...

Loading JSON data into HTML elements using jQuery

I am currently grappling with coding a section where I integrate data from a JSON file into my HTML using jQuery. As a newbie to jQuery, I find myself at a standstill. https://jsfiddle.net/to53xxbd/ Here is the snippet of HTML: <ul id="list"> ...

Tips for converting a "callback pyramid" into a promise-based structure

I'm currently struggling with understanding how to refactor my code to use promises or the Q library effectively. Let's consider a common basic example: I have a test case that imports the same file twice into a MongoDB database and then checks ...