Manipulating arrays with added and removed bound class methods

let array: any[] = [];
class Test {
    constructor() {
        // adding a bound method to the array
        array.push(this.testMethod.bind(this));
        
        console.log('xxx', array); // expecting [ [Function: bound ] ], actually getting [ [Function: bound ] ]
        
        // removing bound method from the array using filter
        array = array.filter(f => f !== this.testMethod.bind(this));
        
        // filter did not work as expected, method still present in the array
        console.log('xxx', array); // expecting [], but getting [ [Function: bound ] ]
    }
    public testMethod(): void {
        return undefined;
    }
}

I am experimenting with adding and removing bound methods from arrays. Although I used a filter to remove the method, it seems to persist. Can anyone shed light on a possible scope issue here?

Answer №1

Each time you use .bind, a new function is created. Invoking this.testMethod.bind(this) twice will result in two distinct functions being generated, not the same function repeated.

Therefore, in the given line of code:

array.filter(f => f !== this.testMethod.bind(this));

It evaluates each element in the array against a freshly crafted function. As the elements within the array are always different from this newly created function, all elements in the array remain untouched by the filter.

To make the filtering operation effective, simply generate one function like so:

let array = [];
class Test {
    constructor() {
        const boundFn = this.testMethod.bind(this)
        array.push(boundFn);
        
        console.log('xxx', array);
        
        array = array.filter(f => f !== boundFn);
        
        console.log('xxx', array);
    }
    testMethod() {
        return undefined;
    }
}

new Test()

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

After a period of running NodeJS and AngularJS together, I am encountering the net::ERR_CONNECTION_RESET error

My setup includes Express with NodeJS and AngularJS on the front-end. However, after performing a series of actions such as adding data, updating records, and showing a list, I encounter the error net::ERR_CONNECTION_RESET. Interestingly, this error only o ...

Transforming a "type containing promises as property values" in Typescript into a "type containing resolved promise values as properties"

Can this be achieved in Typescript? I am looking to transform something like the following: interface IPromiseObject { promiseA: Promise<number>; promiseB: Promise<string>; } Into this: interface IResolvedPromiseObject { promiseA: ...

Can we determine if scrollIntoView is compatible with different browsers through testing?

I am searching for a method to conduct a real-time assessment of the scrollIntoView feature in my user's browser. This is not a simple "caniuse" check; instead, I want to implement graceful degradation. I am utilizing jQuery and would prefer to utiliz ...

Establish a connection to couchDB using JavaScript on the server side

I'm working on a piece of code that involves using Restify to set up a server in node.js and create specific routes. My goal is to interact with CouchDB by performing actions such as GET, POST, DELETE, and PUT. var restify = require("restify"); var s ...

Issue with Counting Digg Button Clicks

I can't figure out why the digg button counter isn't working. I followed the instructions but... The website in question is: . I implemented the code exactly as explained here: But the counter remains at 0. Has anyone encountered a similar iss ...

Is there a way to automatically set all object properties to false if one property is set to true in React?

The Issue: My task at work involves creating 3 buttons with separate filters to display different tickets in a table. All the functionality is completed, and the filtered tickets are displayed correctly. However, I am facing an issue that is preventing m ...

Setting the startup value does not automatically select the value

Check out this angular.js example I created to demonstrate my issue: example I am trying to set the initial value of a select element to a specific value. <select name="i" id="i" ng-model="selectedItem"> <option ng-repeat="i in items ...

transforming JSON key names by associating them with their corresponding JSON values and modifying the key names

My challenge lies in converting a JSON string from one format to another. The initial format is: [ { clientIDs: "WELL #6", analyteIDs: [ "7440-62-2", "7440-28-0" ] } ] ...

Make TypeScript parameter optional if it is not supplied

I am working with an interface that defines scenes and their parameters: export interface IScene<R extends string> { path: R; params?: SceneParams; } The SceneParams interface looks like this: export interface SceneParams { [key: string]: s ...

An element generated using a JavaScript loop is covering another element in the layout

I am facing an issue with positioning images within a div to a span. The problem arises as the images are overlapping each other and I am uncertain about how to properly place each image when it is added. Below is the code snippet: The CSS: <style ty ...

Bootstrap doesn't support Google Fonts

Below are the Google Fonts links I am using: <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fo ...

Encountering a 403 status code from the Spotify Web API while attempting to retrieve data using an OAuth 2.0 Token

I'm currently experimenting with the Spotify Web API and attempting to retrieve my most played songs. To obtain an access token for making requests, I am utilizing the client credentials OAuth flow. While I have successfully obtained the access token, ...

Similar to curl's "resolve" feature, how can we achieve the same functionality in an HTML/JavaScript webpage?

My current setup involves using an ingress controller that requires me to specify a resource using the --resolve feature in curl in order to access certain endpoints. For example, when making a request without specifying the resolution, it fails: curl htt ...

Should I install @capacitor/android as a dev dependency in the package.json file of a React project?

I was pondering whether it would be better to add @capacitor/android, @capacitor/ios, and @capacitor/core as development dependencies. ...

You cannot pair Reanimated 2 withSequence using a direct value

Trying to implement withSequence with a direct value as the initial input resulted in crashing the application. animatedValue.value = withSequence(startValue, withTiming(endValue)); Although the following code appeared to be functioning correctly, it did ...

Using double quotes in a label triggers a browser error displaying "Invalid Label"

Recently, I encountered issues with my browser while parsing JSON return data from the server. Initially, I assumed it was related to my specific data, but even a simple example like {"a": 1} led to an error "invalid label" in Firefox and "SyntaxError: U ...

How do I incorporate a smooth transition effect for opacity in this slideshow code? Part Two

Sorry to bring this up again, but I have made some progress since yesterday. However, I am still unable to complete it, and I'm starting to feel a bit desperate. If you recall, the question I posted yesterday can be viewed here: How can I add opacity ...

Issue with callback function causing incorrect type inference

Here is a simplified code snippet: interface Store<T> { value: T } type AnyStore = Store<any> type StoreValue<T> = T extends Store<infer V> ? V : never function computed< V, D extends AnyStore, S extends Store<V> ...

Using JavaScript, insert unique texts into div elements with the same id

I am working with 5 divs that have the id of "correctAnswer". In my array, I have 5 elements. How can I insert these 5 elements into the 5 divs? Here is the approach I am taking. var answers =["David Bowie","AM","Australia","Boneface","Sound City"]; for ...

"Utilizing Ramda's map function to integrate dynamic keys: A step-by-step guide

I am currently working with an array structured like this : array = ['2020-06-03', '2020-06-05', '2020-06-06'] My task is to transform it into the following format : Object { "2020-06-03": Object { "selec ...