为了账号安全,请及时绑定邮箱和手机立即绑定

原型函数和javascript中的绑定

原型函数和javascript中的绑定

MMTTMM 2019-04-17 13:15:41
我正在学习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 undefinedlet human = new Human('male', 30);human.printInfo();human.printGender();human.printAge();
查看完整描述

2 回答

?
慕盖茨4494581

TA贡献1850条经验 获得超11个赞


因为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.age

human.printAge() // 30

该功能age目前存在的事实test可以作为一个红鲱鱼,让你认为它的this内部只能参考test。事实并非如此。此代码段也有效,它反映this了根据调用上下文查找的行为:


const printAge = function () {

  console.log(this.age)

}


let human = new Human('male', 30)

human.printAge = printAge

human.printAge() // 30


查看完整回答
反对 回复 2019-05-17
  • 2 回答
  • 0 关注
  • 422 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信