第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

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

function.call() 返回全局 this

function.call() 返回全局 this

肥皂起泡泡 2021-11-04 10:32:36
我正在嘗試將用戶對象綁定為 this 并將默認時間綁定為使用function.call方法的第一個參數(shù)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!');為什么此代碼返回未定義的名稱。在節(jié)點 10.16.0.0 中運行[18:21] undefined : hey!
查看完整描述

2 回答

?
慕桂英3389331

TA貢獻2036條經(jīng)驗 獲得超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!

您可以在此處查看有關(guān)部分函數(shù)的更多信息


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

TA貢獻1995條經(jīng)驗 獲得超2個贊

好的,謝謝大家的建議和意見。我想我發(fā)現(xiàn)我做錯了什么。


我將綁定函數(shù)的返回值存儲在 txt 變量中,該變量丟失了this. 我必須做的是用user.txt返回函數(shù)替換或者將它存儲在另一個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



這個很好用。


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


查看完整回答
反對 回復(fù) 2021-11-04
  • 2 回答
  • 0 關(guān)注
  • 157 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號