我试图使用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!发布于 2019-10-01 08:09:01
好的,各位,谢谢你们的建议和意见。我想我发现了我做错了什么。
在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这个很好用。
对不起大家的麻烦,我在做实验:)
发布于 2019-09-30 12:44:23
您想要做的事情实际上是由本机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!您可以查看有关部分函数这里的更多信息。
https://stackoverflow.com/questions/58167929
复制相似问题