为了账号安全,请及时绑定邮箱和手机立即绑定

function.call() 返回全局 this

function.call() 返回全局 this

肥皂起泡泡 2021-11-04 10:32:36
我正在尝试将用户对象绑定为 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!
查看完整描述

2 回答

?
慕桂英3389331

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!

您可以在此处查看有关部分函数的更多信息


查看完整回答
反对 回复 2021-11-04
?
拉风的咖菲猫

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



这个很好用。


对不起大家的麻烦,我正在试验:)


查看完整回答
反对 回复 2021-11-04
  • 2 回答
  • 0 关注
  • 131 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信