【问题标题】:function.call() return global thisfunction.call() 返回全局 this
【发布时间】:2019-09-30 12:28:24
【问题描述】:

我正在尝试使用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!

【问题讨论】:

  • 您正在绑定this 中的bind() { ... },即undefined/window
  • 为什么要手动重新实现bind
  • 你想要做的也可以像这样:function bind(...args){ return Function.prototype.bind.call(...args) }
  • 也许,您可以使用.call.apply 的标准语法,因为它将this 作为第一个参数,您可以对bind 函数执行相同的操作。将user 作为第一个参数。
  • 你也可以这样做:let bind = Function.prototype.call.bind(Function.prototype.bind);

标签: javascript node.js function


【解决方案1】:

你想做的其实是原生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!

你可以查看更多关于偏函数here

【讨论】:

    【解决方案2】:

    好的,谢谢大家的建议和cmets。我想我发现我做错了什么。

    我将绑定函数的返回值存储在 txt 变量中,该变量丢失了 this 我要做的是将 user.txt 替换为返回函数或将其存储在另一个 @ 987654323@ 对象值如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
    
    
    

    这个很好用。

    抱歉给大家添麻烦了,我在做实验:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-07-23
      • 2014-04-12
      • 1970-01-01
      • 2015-09-29
      • 1970-01-01
      • 2017-06-23
      • 2011-11-19
      • 1970-01-01
      相关资源
      最近更新 更多