如何绑定“ this”以减少?

时间:2018-12-28 14:56:31

标签: javascript

我有一个简单的化简器,如何从外部绑定this以便在化简器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;
}, []);

3 个答案:

答案 0 :(得分:8)

显式绑定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), []);

使用关闭/引用

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;
}, []);

使用本身没有this ES6箭头功能,保留“外部”内容:

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

答案 1 :(得分:2)

使用ES6 arrow function,因为它们在lexical scope中工作,因此this的确定取决于其写入的“位置”:

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

也可以在这里查看:How to access the correct `this` inside a callback?

答案 2 :(得分:1)

如果您不能使用arrow functions,则可以将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), []);

另一种方法是将this存储在另一个变量中并使用词法作用域:

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

两种方法都很好。