在javascript中使用bind
如何在下面的代码中使用bind(),这样我就不会失去“this”的作用域 像这样试试 如果我错了,请告诉我在javascript中使用bind,javascript,scope,bind,Javascript,Scope,Bind,如何在下面的代码中使用bind(),这样我就不会失去“this”的作用域 像这样试试 如果我错了,请告诉我 this.getContactName(id, (error, contactName) => { if (error) return callback(error, null); // want to access "this" here e.g., // this.indexScore = 1 return callback(null, contactNam
this.getContactName(id, (error, contactName) => {
if (error) return callback(error, null);
// want to access "this" here e.g.,
// this.indexScore = 1
return callback(null, contactName);
}).bind(this);
您可以像这样使用call()
或apply()
:
this.getContactName(id, (error, contactName) => {
if (error) return callback.call(this, error);
// want to access "this" here e.g.,
// this.indexScore = 1
return callback.call(this, contactName);
});
或使用apply()
这两种方法都将第一个参数绑定为
this
值。区别在于,apply()
有一个函数参数数组作为第二个参数,而call()
只比初始函数调用多了一个参数(第一个参数是函数的this
值)。有关更多信息,请参见此部分。简单的答案是将匿名函数用括号括起来,然后对其调用bind(this)
:
this.getContactName(id, ((error, contactName) => {
if (error) return callback(error, null);
return callback(null, contactName);
}).bind(this));
更微妙的回答是,箭头函数不绑定它们自己的
this
——它们是“词汇范围”——因此实际上不需要这样做。this.indexScore=1
-哪里是indexScore
?您想绑定此的值是多少?[已删除的注释--我没有注意]
this.getContactName(id, (error, contactName) => {
if (error) return callback.apply(this, [ error ]);
// want to access "this" here e.g.,
// this.indexScore = 1
return callback.apply(this, [ contactName ]);
});
this.getContactName(id, ((error, contactName) => {
if (error) return callback(error, null);
return callback(null, contactName);
}).bind(this));