What is the technique for accessing the original function within a class using a proxy?

I attempted to monkey patch a function within my class using Proxy.

Is there a way to access and execute the original function?

class foo {
  x = 10;

  bar() {
    console.log({ x: this.x });
  }
}

foo.prototype.bar = new Proxy(foo.prototype.bar, {
  apply: function() {
    console.log("xxx");
    console.log({ that: this });

    this.bar();
  }
});

new foo().bar();

Check out the code on StackBlitz

Answer №1

According to the MDN documentation, the handler’s apply is invoked with the original function as a parameter:

class example {
  y = 20;

  baz() {
    console.log({ y: this.y });
  }
}

example.prototype.baz = new Proxy(example.prototype.baz, {
  apply: function(target, thisArg, argumentsList) {
    console.log("yyy");
    Reflect.apply(target, thisArg, argumentsList);
  },
});

new example().baz();

(Typically, the Reflect functions can be utilized to delegate to the proxy trap with the same name.)

It is worth noting that, as is often the case with proxies, they may not be necessary.

class example {
  y = 20;

  baz() {
    console.log({ y: this.y });
  }
}

const originalBaz = example.prototype.baz;

Object.assign(example.prototype, {
  baz() {
    console.log("yyy");
    originalBaz.call(this);
  },
});

new example().baz();

Answer №2

It's important to note that the this within your apply function is referring to its own scope, specifically the function itself.

You have the option to pass parameters to the apply function as shown below:

apply: function(target, that, args) { ... }

In this context, the target represents the bar function, the that is a reference to the parent object, and args is... well, you can probably guess :-)

class foo {
  x = 10;

  bar(value) {
    console.log('Class variable x: ', x);
    console.log('Method Parameter: ', value)
  }
}

foo.prototype["_bar"] = foo.prototype.bar;

foo.prototype.bar = new Proxy(foo.prototype.bar, {
  apply: function(target, that, args) {
    console.log("Target", target);
    console.log("THAT", that);
    console.log("args", args);
  }
});

new foo().bar('World');

If you were to call target.bar(args) within your apply function, it would result in an infinite loop.

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

Problem with Angular 2 Typings Paths in Typescript

Currently, I am in the process of learning how to create a Gulp build process with Angular 2 and Typescript. Following the Quick Start guide has allowed me to get everything up and running smoothly. However, I have decided to experiment with different fold ...

Restrict Material-UI DatePicker to only allow the selection of the year using react

Struggling to configure a Material-UI DatePicker to only accept the year without letting the user input or select the month and day. I've attempted various solutions but nothing seems to be working. Does anyone know how to solve this issue? ...

Issue with NgModule in Angular application build

I'm facing an issue with my Angular application where the compiler is throwing errors during the build process. Here's a snippet of the error messages I'm encountering: ERROR in src/app/list-items/list-items.component.ts:9:14 - error NG6002 ...

Selecting Elements with jQuery OR JavaScript

Question: jQuery attribute selector for multiple values I am facing a query regarding jQuery attribute selection. Here is the code snippet I have: $('input:radio[name=foo]').change(function() { blah(); }); $('input:radio[name=bar] ...

Is there a way to access the Flask global in AngularJS?

I'm in the process of developing an internal web application using Flask that connects to various clusters. The majority of the URLs begin with /cluster/cluster_name, which is why I've implemented the following code in my blueprints: cluster = B ...

Error encountered: X.setValue is not a valid function and cannot be used to set the value. However, manually inputting the value as a

When I try to use the line sseTopicString.setValue(sseValueNumber), a Type error is thrown: Uncaught TypeError: sseTopicString.setValue is not a function. Interestingly, if I output the value (string) of sseTopicString before the dot, everything works fin ...

Retrieve data from dropdown menu to showcase table using Node.js

I'm currently diving into learning nodejs and mongodb. My backend setup includes expressjs and mongojs, while ejs is handling the frontend of my application. The main goal is to allow users to select a class from a dropdown menu and view a correspondi ...

Ensure that the div remains within the viewport

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Tit ...

Angular: Navigating through two levels of fetched data from Firebase

I'm currently working on parsing retrieved data from Firebase within an Angular (Typescript) project. The structure of my JSON data in Firebase resembles the following: "customer" : { "customerId1" : { "documents" : { "documentId1" : { ...

modifying button depending on the state of bootstrap collapse

I'm currently utilizing Bootstrap in my project. Here is the snippet of HTML code I have: <div class="row"> <button id="dog-btn" data-toggle="collapse" data-target="#dog-section" onclick=" ...

Is it possible to toggle between namespace and class using parentheses?

While working with older javascript code, I stumbled upon the following snippet: // module1.js class Class { constructor() { console.log('hello') } } const exported = { Class: Class, } module.exports = exported This code is then ...

Is there a way to access various history.pushState events when using window.popState in JavaScript?

In my code, there are two pushStates that I need to read separately and execute different functions for. However, when the form is not submitted, the related pushState does not trigger and results in this error: Uncaught TypeError: Cannot read property &ap ...

Retrieve the text input from its respective radio button

There are two radio buttons, each accompanied by an input text field. When a user selects a radio button, they can also enter some corresponding text. My inquiry is: What is the best method to retrieve the entered text for the selected radio button? ...

Using the spread operator to modify an array containing objects

I am facing a challenge with updating specific properties of an object within an array. I have an array of objects and I need to update only certain properties of a single object in that array. Here is the code snippet I tried: setRequiredFields(prevRequir ...

Vue Testing Utilities - issue with data not updating upon click event activation

I recently created a basic test using Vue Test Utils: import { mount } from '@vue/test-utils' const App = { template: ` <p>Count: {{ count }}</p> <button @click="handleClick">Increment</button> `, ...

How can I generate a fresh window/frame within my Javascript canvas?

Is there a way to open a new frame or window within the canvas using JavaScript? I am working on a game project where I want to implement a feature that displays additional information on a menu screen when a button is pressed. Currently, I have managed to ...

Route is not simply a component in this context. When using Routes, all component children must be either a Route or wrapped within

I am currently working on my App.js file and encountering an issue while creating paths. I have wrapped a Route element around my IsUserRedirect, but the error persists. import React, {Fragment} from 'react'; import * as ROUTES from './cons ...

Retrieve the implementation of an interface method directly from the constructor of the class that implements it

I am looking to create a function that takes a string and another function as arguments and returns a string: interface Foo { ConditionalColor(color: string, condition: (arg: any) => boolean): string; } I attempted to pass the ConditionalColor metho ...

Having trouble linking the date object with the default value of the date input field

Exploring how to set the default value of a date type input using property binding. Initially, I attempted to create a new date object in app.component.ts and then bind the [value] attribute of the date input to the currentDate property within app.compone ...

Transferring information from RSC to a nested child component using the Next.js application router

Currently, I am in the process of migrating a large Pages router next.js project to the App directory. However, I have encountered a common challenge for which I am struggling to find a suitable solution. Despite being accustomed to the convenience of Reac ...