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
添加回答
舉報
0/150
提交
取消