Access to private members is restricted when redefining a class method

After defining a private member with #, attempting to redefine a member that utilizes this private member will result in the inability to access it:

class Foo {
    #secret = "Keyboard Cat";
    
    method() {
        console.log(this.#secret);
    }
}

const target = Foo.prototype;
const key = "method";

const desc = Object.getOwnPropertyDescriptor(target, key);

const og = desc.value;

desc.value = function (...args) {
    return og.apply(target, args);
};

Object.defineProperty(target, key, desc);

new Foo().method();

Uncaught TypeError: Cannot read private member #secret from an object whose class did not declare it

Why is this happening? I simply wrapped the original method in this case. Keep in mind that this example is a greatly simplified version of using decorators with TypeScript. Is there a way to work around this limitation while still being able to modify and "alter" the method?


Here is the same scenario, but with a TypeScript decorator:

const Curse: MethodDecorator = (target, _, desc) => {
    const og = desc.value as Function;

    desc.value = function (...args: any[]) {
        return og.apply(target, args);
    } as any;

    return desc;
};

class Foo {
    #secret = "Keyboard Cat";
    
    @Curse
    method() {
        console.log(this.#secret);
    }
}

new Foo().method();

Playground

Answer №1

The error occurred because you applied the method to Foo.prototype instead of the new Foo instance using the this keyword:

class Foo {
    #secret = "Keyboard Cat";
    
    method() {
        console.log(this.#secret);
    }
}

const target = Foo.prototype;
const key = "method";

const desc = Object.getOwnPropertyDescriptor(target, key);

const orig = desc.value;

desc.value = function (...args) {
    return orig.apply(this, args);
//                    ^^^^
};

Object.defineProperty(target, key, desc);

new Foo().method();

Foo.prototype does not contain the private field #secret. The same error will occur with

class Foo {
    #secret = "Keyboard Cat";
    
    method() {
        console.log(this.#secret);
    }
}

Foo.prototype.method();

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

Remove image files from a directory with jQuery without relying on PHP or AJAX

Did you know that JQuery code is capable of executing unlink operations like PHP without using AJAX or a PHP file? For instance, if you wish to delete or unlink the file "aaa.jpg" located in the folder www.myproject.com/images/, you can achieve this by s ...

Can the ElasticSearch standard Node client be considered secure for integration with cloud functions?

When working with my Typescript cloud functions on GCP, I have been making direct HTTP requests to an ElasticSearch node. However, as my project expands, I am considering switching to the official '@elastic/elasticsearch' package for added conven ...

Error message: The function r is not defined - Issue with Google Sign in on React app

I have successfully implemented Google Sign In for my react app during development, but I am facing an issue with it in the production environment. The npm module that I am using for Google authentication is available at https://www.npmjs.com/package/reac ...

Combine a main document with a document located within its sub-collection

I am managing a database within firestore that has the following structure: -> Chat Room -> Users Within the "ChatRoom" collection, there is a "Users" collection. Each document in the users collection includes a field "read: true/false" to trac ...

Tips for accessing user-defined headers within CORS middleware

I've developed a CORS middleware utilizing the CORS package. This middleware is invoked before each request. Here's how I implemented it: const corsMiddleware = async (req, callback) => { const { userid } = req.headers|| req.cookies {}; l ...

JQuery Keyup event is not functioning as expected

For my blog navigation, I have set up an event where pressing the 'J' key takes me to the previous post and the 'K' key takes me to the next post. However, I am facing an issue where the event works initially but stops working after the ...

Is there a way for me to streamline the process of logging in using either Google or Facebook?

Is there a way for me to automate the scenario if I'm unable to locate the element using Appium Uiautomator? https://i.stack.imgur.com/Rjji4.png ...

Troubarked by problems NodeJS faces when trying to establish a connection with CosmosDB using a connection

Having trouble with my code that fails when I try to create a new instance of the CosmosClient. The option to create a CosmosClient using a connection string should be straightforward. The environment variable holds the necessary connection string in this ...

Found inconsistent results when running a npm script globally versus inline

After running some tests, I discovered that tslint is functioning correctly when using the following command: tslint -c tslint.json --project tsconfig.json 'src/**/*.ts' However, when attempting to integrate it into an npm script, it appears th ...

Issue with React Routes only occurring in the production website

I'm encountering an issue on my personal website that only occurs in production, but not in my local environment. Here's the situation: I have set up the routes as follows const Routes = () => ( <Router> <Route exact path=&quo ...

What is the best way to prioritize a non-submit button over a submit button in material-ui?

I am facing an issue with a form on my website. Whenever I press the enter key, the form is automatically submitted. Everything seems to be working fine so far. However, there is a specific scenario where if a user selects a certain option in the form, it ...

What is the method for obtaining cross-domain data with Javascript within a django framework?

Picture this scenario: you have two domains and you're looking to enable communication between them using Javascript. Currently, I have set up two servers on separate ports on my local machine. While it appears that the request is being successfully ...

The saving function of the Jquery camera is not working properly and does not store the

I seem to be having an issue when using the jquery camera in "save" mode. Despite trying to call the url in "webcam.save" manually, it doesn't seem to have any effect. It appears that the jquery camera plugin may not be functioning as intended. Any su ...

The Ionic tab is already finished displaying even before the data has completed loading

Creating a favorites section for a vouchers app has proven to be slightly challenging. When attempting to retrieve the current user's favorite vouchers and display them using ngFor in the HTML, I encountered an issue. The very first time I open the fa ...

The compatibility issue between Rails 7 and Bootstrap 5.2.3, along with importmaps JavaScript, is causing dysfunction in the

Feeling a bit lost here, as I've tried several solutions from Stack Overflow related to getting bootstrap 5.2.3 javascript to work for a dropdown menu. Importmaps seem like the best approach, although esbuild was attempted with no luck. Below is a sn ...

Subcomponent in React is not rendering as expected

I have a primary React component with a subcomponent named AttributeInput. To prevent redundancy in my code, I moved some of the logic from the main component to a method within AttributeInput. My attempt at referencing this code looks like this: {this.s ...

Renaming personalized elements in Aurelia templates

My inquiry pertains to the process of aliasing custom elements and integrating them into aurelia's html-templates. To set the scene, I am utilizing the latest webpack typescript skeleton available at https://github.com/aurelia/skeleton-navigation and ...

Challenging glitch in the JavaScript code

My jQuery code seems to be functioning properly in online text editors like Fiddle and StackOverflow snippets. However, when I try to implement the same code in Brackets or view it on GitHub, the navbar scroll down animation fails to work as expected. You ...

Utilize Vue.js to send bound data to a click event

I am currently working with a v-for loop that iterates over data fetched from an API, setting the key as the ID of each object. My goal is to create a click event that captures the v-bind:key value of the clicked element. This will allow me to locate all t ...

Is it possible to access an external JavaScript file in the main.js by importing it?

In this scenario, I have defined an array of countries in an external Javascript file. const countries = [ "Australia", "Brazil", "China", "Denmark", "Egypt", "France", "Germany", "Hungary", "Italy", "Japan", ...