亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

原型函數和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 關注
  • 435 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號