繁体   English   中英

原型函数和javascript中的绑定

[英]prototype function and bind in 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();

@noa-dev是正确的,因为bind调用中的this并不是指你想要的。

您可以简单地为原型提供功能,并且它可以正常工作:

Human.prototype.printAge = test.age

test.age的函数定义中,它要求this.age 在这种情况下, this是由函数调用的调用上下文定义的。 通过将test.age放在Human的原型上, Human实例调用human.printAge()它将human作为调用上下文,因此this指的是函数内部的正确内容。

如果将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

想我也可以在这里正确地写出来。 之所以

Human.prototype.printAge = test.age.bind(this); // gives me undefined

给你undefined是,因为在javascript中“this”关键字总是引用下一个更大的包装函数范围。 在您的情况下,窗口范围和窗口很可能不知道类内容。

为了实现您想要的功能,您可以将函数调用绑定到人类实例,如下例所示:

https://jsfiddle.net/v6ye2b0f/1/

class Human {
    constructor(age) {
    this.age = age || 0;
  }
}

const human = new Human(30);

console.log(human.age); // 30;

const ageLogger = function() {
    console.log(this.age);
}


Human.prototype.logAge = ageLogger.bind(human);
ageLogger.call(human); // 30
human.logAge(); // 30

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM