-1

How can I use bind() in the code below so that I dont lose the scope of "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);
});
Asif
  • 393
  • 9
  • 17

3 Answers3

1

You can use call() or apply() like this:

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);
});

Or with apply()

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 ]);
});

Both methods bind the first argument as this value. The difference is, that apply() has an array of function arguments as a second parameter whereas call() just has one more argument than the initial function call (the first one is the functions's this value). See this answer for more information.

ssc-hrep3
  • 15,024
  • 7
  • 48
  • 87
0

Try like this let me know if i'm wrong here

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);
Dinesh undefined
  • 5,490
  • 2
  • 19
  • 40
0

The straightforward answer is to wrap the anonymous function in parentheses and call bind(this) on it:

this.getContactName(id, ((error, contactName) => {

  if (error) return callback(error, null);
  return callback(null, contactName);

}).bind(this));

The more nuanced answer is that arrow functions don't bind their own this -- they are "lexically scoped" -- so this shouldn't actually be necessary.

shabs
  • 718
  • 3
  • 10