Issue
let array: any[] = [];
class Test {
constructor() {
// add bound method to the array
array.push(this.testMethod.bind(this));
console.log('xxx', array); // expect [ [Function: bound ] ], is [ [Function: bound ] ]
// remove bound method from the array
array = array.filter(f => f !== this.testMethod.bind(this));
// did not work, still there
console.log('xxx', array); // expect [], is instead [ [Function: bound ] ]
}
public testMethod(): void {
return undefined;
}
}
I'm looking at adding and removing bound methods from arrays. I expect the method to be removed using a filter
, but it ends up remaining.
Is there a scope issue i'm not aware of here?
Solution
Every time you call .bind
you make a new function. Calling this.testMethod.bind(this)
twice gives you two different functions, not the same function twice.
So when you run this line of code:
array.filter(f => f !== this.testMethod.bind(this));
You are checking each element of the array to see it it matches a brand new function that you just made. The elements of the array will always be different from this new function, so the filter keeps all elements of the array.
If you change your code to just create one function, then the filtering will work:
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()
Answered By - Nicholas Tower
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.