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

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

function.call() 返回全局 this

function.call() 返回全局 this

肥皂起泡泡 2021-11-04 10:32:36
我正在嘗試將用戶對象綁定為 this 并將默認時間綁定為使用function.call方法的第一個參數let user = {  name:'rifat',  txt (time, msg){    console.log('['+time+ '] '+ this.name+ ' : '+ msg);  }}function bind(func, ...fArgs){  return function(...args){    return func.call(this, ...fArgs, ...args);  };}let txt =  bind(user.txt, new Date().getHours()+':' +new Date().getMinutes() );txt('hey!');為什么此代碼返回未定義的名稱。在節點 10.16.0.0 中運行[18:21] undefined : hey!
查看完整描述

2 回答

?
慕桂英3389331

TA貢獻2036條經驗 獲得超8個贊

你要做的其實是原生bind本身支持的。


let user = {

  name:'rifat',

  txt (time, msg){

    console.log('['+time+ '] '+ this.name+ ' : '+ msg);

  }

}


let txt =  user.txt.bind(user, new Date().getHours()+':' +new Date().getMinutes());


txt('hey!');

輸出:


[18:11] rifat : hey!

您可以在此處查看有關部分函數的更多信息


查看完整回答
反對 回復 2021-11-04
?
拉風的咖菲貓

TA貢獻1995條經驗 獲得超2個贊

好的,謝謝大家的建議和意見。我想我發現我做錯了什么。


我將綁定函數的返回值存儲在 txt 變量中,該變量丟失了this. 我必須做的是用user.txt返回函數替換或者將它存儲在另一個user對象值中,例如user.txtBound


代碼的正確版本是


let user = {

  name:'rifat',

  txt (time, msg){

    console.log('['+time+ '] '+ this.name+ ' : '+ msg);

  }

}



function bind(func, ...fArgs){

  return function(...args){

    return func.call(this, ...fArgs, ...args); // here 'this' will be determined 

                                                //when the returned function executes

  };

}


user.txt =  bind(user.txt, new Date().getHours()+':' +new Date().getMinutes() ); 

// storing the returned function as a object property


user.txt('hey!'); //this works fine



這個很好用。


對不起大家的麻煩,我正在試驗:)


查看完整回答
反對 回復 2021-11-04
  • 2 回答
  • 0 關注
  • 151 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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