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
这个很好用。
对不起大家的麻烦,我正在试验:)
添加回答
举报