猿问

原型函数和javascript中的绑定

我正在学习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();


MMTTMM
浏览 423回答 2
2回答

慕盖茨4494581

因为bind呼叫中没有指你想要的东西。您可以简单地为原型提供功能,并且它可以正常工作:Human.prototype.printAge = test.age在函数定义中test.age,它是要求的this.age。在这种情况下,this由函数调用的调用上下文定义。通过放置一个实例调用它test.age的原型作为调用上下文,所以引用函数内部的正确事物。HumanHumanhuman.printAge()humanthis如果test.age直接放在实例上,可以更明显地实现相同的行为:let human = new Human('male', 30)human.printAge = test.agehuman.printAge() // 30该功能age目前存在的事实test可以作为一个红鲱鱼,让你认为它的this内部只能参考test。事实并非如此。此代码段也有效,它反映this了根据调用上下文查找的行为:const printAge = function () {  console.log(this.age)}let human = new Human('male', 30)human.printAge = printAgehuman.printAge() // 30
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答