How to bind `this` to reduce?

  • A+
Category:Languages

I have a simple reducer, how do I bind this from outside to use that inside the reducer this.teacherInstance?

this.teachersDropMenu = this.plans.reduce(function (teacherIdArr, teacher) {   if (teacherIdArr.indexOf(teacher.teacherId) == -1) {      teacherIdArr.push(this.teacherInstance.getTeacherModelById(teacher.teacherId));   }   return teacherIdArr; }, []); 

 


Using explicit binding with Function.prototype.bind:

this.teachersDropMenu = this.plans.reduce(function (teacherIdArr, teacher) {    if (teacherIdArr.indexOf(teacher.teacherId) == -1) {       teacherIdArr.push(this.teacherInstance.getTeacherModelById(teacher.teacherId));    }    return teacherIdArr; }.bind(this), []); 

Using a closure/reference:

const self = this; this.teachersDropMenu = this.plans.reduce(function (teacherIdArr, teacher) {    if (teacherIdArr.indexOf(teacher.teacherId) == -1) {       teacherIdArr.push(self.teacherInstance.getTeacherModelById(teacher.teacherId));    }    return teacherIdArr; }, []); 

Using an ES6 arrow function that doesn't have a this of its own, preserving the "outer" this:

this.teachersDropMenu = this.plans.reduce((teacherIdArr, teacher) => {    if (teacherIdArr.indexOf(teacher.teacherId) == -1) {       teacherIdArr.push(this.teacherInstance.getTeacherModelById(teacher.teacherId));    }    return teacherIdArr; }, []); 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: