Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/batch-file/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在javascript中使用bind_Javascript_Scope_Bind - Fatal编程技术网

在javascript中使用bind

在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

如何在下面的代码中使用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, 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));