Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to bind `this` to reduce?

Tags:

javascript

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;
}, []);
like image 336
OPV Avatar asked Oct 29 '25 09:10

OPV


2 Answers

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;
}, []);
like image 175
connexo Avatar answered Oct 31 '25 07:10

connexo


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?

like image 24
Mohamed Elsayed Avatar answered Oct 31 '25 07:10

Mohamed Elsayed



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!