【发布时间】: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