我正在学习javascript中的绑定。我需要一些帮助。无法使用bind将原型函数与另一个函数连接。如果函数在类中,它就可以工作。
例:
let test = {};
test.gen = function () {
console.log(this.gender);
}
test.age = function () {
console.log(this.age);
}
class Human {
constructor(gender, age) {
this.gender = gender;
this.age = age;
}
printInfo() {
console.log(this.gender);
}
printGender = test.gen.bind(this);
// printAge = test.age.bind(this); // this works
}
Human.prototype.printAge = test.age.bind(this); // gives me undefined
let human = new Human('male', 30);
human.printInfo();
human.printGender();
human.printAge();
慕盖茨4494581
相关分类