我有一个简单的化简器,如何从外部绑定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;
}, []);
答案 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;
}, []);
两种方法都很好。