我的理解是,根据规范,设置的参数bind()
是最终的,不能被覆盖。
我想知道是否有任何方法可以实现这样的目标,但无法给我想要的结果:
const Student = {
name: "",
times: function(i, j) {
return `I am: ${this.name} & think answer is: ${i*j}`;
}
};
const student1 = {
name: "student1"
}
const student2 = {
name: "student2"
}
const askThemTimesBy10 = Student.times.bind(null, 10);
console.log(askThemTimesBy10.bind(student1)(5));
console.log(askThemTimesBy10.bind(student2)(5));
显然这会失败,因为函数上下文在柯里化时是硬编码的。
现在我可以清楚地做一些黑客攻击,比如:
askThemX10 = function(){
return Student.times.bind(this, 10);
}
askThemXTen = function(i){
return Student.times.call(this, 10, i);
}
然后像这样使用它们:
console.log(askThemX10.bind(student1)()(5));
console.log(askThemXTen.bind(student1)(5));
或者我可以在里面定义咖喱函数Student
等等,但我想知道是否有更好的方法来做到这一点。