function.call() 返回全局 this

我正在尝试将用户对象绑定为 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!


肥皂起泡泡
浏览 132回答 2
2回答

慕桂英3389331

你要做的其实是原生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!您可以在此处查看有关部分函数的更多信息

拉风的咖菲猫

好的,谢谢大家的建议和意见。我想我发现我做错了什么。我将绑定函数的返回值存储在 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 propertyuser.txt('hey!'); //this works fine这个很好用。对不起大家的麻烦,我正在试验:)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript