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;
}, []);
Use an ES6 arrow function as they work in lexical scope, so this is determined depending on "where" it is written:
this.teachersDropMenu = this.plans.reduce((teacherIdArr, teacher) => {
if (teacherIdArr.indexOf(teacher.teacherId) == -1) {
teacherIdArr.push(this.teacherInstance.getTeacherModelById(
teacher.teacherId));
}
return teacherIdArr;
}, []);
Also have a look here: How to access the correct `this` inside a callback?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With