2 回答

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!
您可以在此處查看有關部分函數的更多信息

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
這個很好用。
對不起大家的麻煩,我正在試驗:)
添加回答
舉報