[英]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.