How can I use a prototype's method with this
referencing to the prototype in a higher order function like reduce
?
Example code:
function A() {
this.names = ["John", "Jane", "Doe"];
this.printMergedNamesByIndexes = function() {
const indicies = [0,1,2]
console.log(indicies.reduce(this.mergeNames, ""))
};
this.mergeNames = function(accumulator, index) {
return accumulator + this.names[index] + ", "
};
}
const a = new A()
a.printMergedNamesByIndexes()
I'd like to pass the mergeNames
method of the prototype to the reduce
function, but in that case the this value in the mergeNames
method does not reference to the prototype itself. So I got an error:
TypeError: undefined is not an object (evaluating 'this.names[index]')
I found this post: Using prototype functions in higher order functions in javascript , but the bind
method gave me a similar error like above, except it was complaining about the nonexistence of the bind
method.